views:

371

answers:

3

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.

+6  A: 

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!");
});
marcgg
yeah that's great but how do I check which one is checked and grab the value of all the checked ones?
shogun
this.checked
marcgg
A: 
var checkboxes = [];
$('input[type=checkbox]').each(function () {
    if (this.checked) {
        checboxes.push($(this).val());
    }
});
Anatoliy
A: 

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