NoWar
NoWar

Reputation: 37633

How to iterate through all checkboxes on the page?

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!

Upvotes: 2

Views: 9454

Answers (5)

themhz
themhz

Reputation: 8424

$("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
});

Upvotes: 8

jcern
jcern

Reputation: 7848

You can use this to iterate through the checkboxes:

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

Upvotes: 5

jfriend00
jfriend00

Reputation: 707308

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
});

Upvotes: 4

Adil
Adil

Reputation: 148110

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() {

 });

Upvotes: 2

Alex
Alex

Reputation: 9031

$('input[type="checkbox"]').each(function() {
  ...
});

Upvotes: 2

Related Questions