2

如何使用 JQuery 遍历页面上的所有复选框?

即我有checkboxes上面的那些......

<div>
<input checked="checked" type="checkbox" name="option_1" id="checkbox_1" value="1" />35 MM                  
<input checked="checked" type="checkbox" name="option_2" id="checkbox_2" value="2" />  DIGITAL                    
<input type="checkbox" name="option_3" id="checkbox_3" value="3" /> 3D DIGITAL
</div>

我用过吗

 $('input[id^="checkbox_"]').each(function() {

 });

这是对的吗?谢谢!

4

5 回答 5

8
$("input[type='checkbox']").each(function(){
  var name = $(this).attr('name'); // grab name of original
  var value = $(this).attr('value'); // grab value of original
  var ischecked = $(this).is(":checked"); //check if checked
});
于 2012-08-14T13:50:24.747 回答
5

您可以使用它来遍历复选框:

$("input:checkbox").each(function() {
    alert($(this).val());
   });
于 2012-08-14T13:57:35.073 回答
4

jQuery supports a selector :checkbox that is just for selecting checkboxes on the page so if you want all checkboxes on the page that's the simplest way to do it:

$(":checkbox").each(function(index, element) {
    // put your code here
});

In the jQuery doc for :checked, they recommend that this selector might perform slightly faster:

$("input[type='checkbox']").each(function(index, element) {
    // put your code here
});
于 2012-08-14T13:48:54.537 回答
2
$('input[type="checkbox"]').each(function() {
  ...
});
于 2012-08-14T13:48:44.413 回答
2

It seem alright but you can add further type check to ensure not other control type with mataching id comes in selector.

$('input[type=checkbox][id^="checkbox_"]').each(function() {

 });
于 2012-08-14T13:49:06.820 回答