views:

44

answers:

3

Given a form (id = "my_form"), how do I loop over all checkboxes of the form, checking if the given one is checked or not and grabbing its name/value?

I know how to check a checkbox status given its value, but I need to loop without knowing in advance which checkboxes exist. Thanks.

A: 

the following code will loop over all of the checked checkboxes.

$(':checkbox', '#my_form').filter(':checked').each(function(){
    var name = $(this).val();
});
Naeem Sarfraz
TypeError: Object false has no method 'each'... That's caused by is() not returning this.
AutoSponge
@AutoSponge: that's because *is()* tests the collection against a selector and returns a boolean (true or false). For the purposes of this answer *filter()* should be used instead of *is()*.
Andy E
@Andy E, thanks for the pointer
Naeem Sarfraz
+1  A: 

Example: http://jsfiddle.net/C6Kau/

$('#my_form :checkbox').each(function(){
     if( this.checked ) {
          alert( 'checked: ' + this.name + ' ' + this.value );
     } else {
          alert( 'Not checked: ' + this.name + ' ' + this.value );
     }
});
patrick dw
A: 
var box, boxes = $('#myform :checkbox'), i = boxes.length;

while (i--) {
    box = boxes[i];
    if (box.checked) {
        alert ("I'm checked");
    } else {
        alert ("I'm not checked");
    }
}
AutoSponge