MetaGuru
MetaGuru

Reputation: 43873

How do I use jQuery to loop through an unspecified number of checkboxes?

I need to loop through a div full of an unknown number of checkboxes and get back the values of the checkboxes that are checked, how do I do this with jQuery? I guess it should happen onchange of any of the checkboxes.

Upvotes: 4

Views: 14822

Answers (3)

Ender
Ender

Reputation: 15231

Try:

<div id="blah"> 
  <input type="checkbox" class="mycheckbox" />
  <input type="checkbox" class="mycheckbox" />
  <input type="checkbox" class="mycheckbox" />
</div>

$("#blah .mycheckbox:checked").each(function(){
  alert($(this).attr("value"));
});

Upvotes: 5

Anatoliy
Anatoliy

Reputation: 30103

var checkboxes = [];
$('input[type=checkbox]').each(function () {
    if (this.checked) {
        checboxes.push($(this).val());
    }
});

Upvotes: 2

marcgg
marcgg

Reputation: 66535

Just do:

<div id="blah"> 
  <input type="checkbox" class="mycheckbox" />
  <input type="checkbox" class="mycheckbox" />
  <input type="checkbox" class="mycheckbox" />
</div>

$("#blah .mycheckbox").each(function(){
  alert(this + "is a checkbox!");
});

Upvotes: 8

Related Questions