2

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.

3 Answers 3

1

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 );
     }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

$(':checkbox', '#my_form').filter(':checked').each(function(){
    var name = $(this).val();
});

2 Comments

TypeError: Object false has no method 'each'... That's caused by is() not returning this.
@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().
0
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");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.