0

我需要在一个 html 页面中获取所有选中的项目并将它们放在一个数组中以对其执行特定操作。我不明白复选框的字段(名称,值,...)。我在rails上使用带有ruby的html!

4

3 回答 3

0

如果您需要使用 javascript 在客户端执行此操作,您可以像这样使用 jQuery:

var arr = $('[type=checkbox]:checked');

如果您需要在服务器端使用 ruby​​ on rails 执行此操作,我无法帮助您。但是我知道只有选中的复选框才会通过 GET 或 POST 发送回服务器,所以如果您知道这些复选框的名称,您可以从请求对象中获取它们并将它们放入数组中。未选中的复选框永远不会到达服务器,因此您不必显式忽略它们。

于 2012-04-18T22:53:06.387 回答
0

如果你做这样的事情:

<input type='checkbox' name='User[]' VALUE='someVal'>Visible Text</option>

用户选中然后提交的任何复选框都将位于名为 User 的 POST 数组中。

提交时将 [ ] 添加到名称中会创建一个数组。

不确定在 ruby​​ on rails 中但在 php 中这样做很热。当提交表单但用户将一个数组传递给服务器时。我们将复选框命名为 User,因此我们发布的数组称为 User。在 php 中,我检索发布的数组,如下所示:

print_r($HTTP_POST_VARS["User"]); 

然后这会像这样输出数组:

Array ( [0] => Me [1] => You [2] => SomeoneElse ) 

数组中的所有数据都是复选框。你可以做一个

foreach (​​​​​​​ $HTTP_POST_VARS["User"] as $key => $value) { $key is 0, $value is Me. and so on } 

希望这会有所帮助——</p>

于 2012-04-18T23:29:12.223 回答
0

$_POST is already an array of everything within the form set. Use this to do your "certain action" on the checkboxes. If for whatever reason you need the information in a different variable, then just loop through the $_POST and put it into a different variable like so:

while ($row = $_POST) {
   $new_var[] = $row[0];
}

That should work for you to put into a new/different array but frankly, I don't see the point of that since it's already an array.

As far as understanding the way the array of $_POST looks like, then var_dump() it and see. The name of the checkbox will be that in [] and the value will display after the =>. So if your input is named name=box1 and the value is value=1 then the array, from the $_POST standpoint, would look like [box1] => 1 so you can then use this section by calling it specifically like $foo = $_POST['box1'] and the value of $foo would be the value of box1 or you can do whatever else you want with that (rather than put into a new variable) by calling it.

于 2012-04-18T23:37:45.243 回答