views:

213

answers:

4

How do I know, using jQuery, if all or none of the following checkboxes have been selected?

Soccer: <input type="checkbox" name="sports" value="soccer" style="chkbox" /><br />
Football: <input type="checkbox" name="sports" value="football" style="chkbox" /><br />
Baseball: <input type="checkbox" name="sports" value="baseball" style="chkbox" /><br />
Basketball: <input type="checkbox" name="sports" value="basketball" style="chkbox" />
+6  A: 

Using jQuery...

var sportsCheckboxes = $("input[name=sports]");
var checkedSports = $(":checked", sportsCheckboxes);
var all = (sportsCheckboxes.length == checkedSports.length);
var none = (checkedSports.length == 0);
Josh Stodola
+2  A: 

Maybe something like this:

if ($("input:checkbox:checked").length == 4) {
    // do something
}
else if ($("input:checkbox:checked").length == 0) {
    // do something else
}
adamse
I like the structure of this answer, but could be better as:if ($("input[name=sports]:checkbox:checked").length == $("input[name=sports]:checkbox").length ) This would avoid the hard coded value.
Mark Schultheiss
+1  A: 
alert($("input[name=sports]:checked").length);
Aaron
A: 
var checkedBoxes = $('input:checkbox:checked').length;

if(!checkedBoxes) {
    // None checked
} else if(checkedBoxes == $('input:checkbox').length)  {
    // All checked
}

Note: Putting case for having no checkboxes checked first since it is more likely. This is a minor optimization.

gvn