最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to iterate through all checkboxes on the page? - Stack Overflow

programmeradmin7浏览0评论

How do I can iterate through all checkboxes on the page with JQuery?

I.e. I have those checkboxes above...

<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>

Have I use

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

 });

Is it correct? Thank you!

How do I can iterate through all checkboxes on the page with JQuery?

I.e. I have those checkboxes above...

<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>

Have I use

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

 });

Is it correct? Thank you!

Share Improve this question asked Aug 14, 2012 at 13:47 NoWarNoWar 37.6k82 gold badges338 silver badges514 bronze badges 1
  • Assuming you only want inputs that have an ID beginning with "checkbox_" then yes, that code is correct. – Anthony Grist Commented Aug 14, 2012 at 13:49
Add a ment  | 

5 Answers 5

Reset to default 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
});

You can use this to iterate through the checkboxes:

$("input:checkbox").each(function() {
    alert($(this).val());
   });

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 remend that this selector might perform slightly faster:

$("input[type='checkbox']").each(function(index, element) {
    // put your code here
});
$('input[type="checkbox"]').each(function() {
  ...
});

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

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

 });
发布评论

评论列表(0)

  1. 暂无评论