How do you know using JQuery when either all or no checkboxes have been selected
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: <inpu开发者_开发百科t 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" />
Using jQuery...
var sportsCheckboxes = $("input[name=sports]");
var checkedSports = $(":checked", sportsCheckboxes);
var all = (sportsCheckboxes.length == checkedSports.length);
var none = (checkedSports.length == 0);
Maybe something like this:
if ($("input:checkbox:checked").length == 4) {
// do something
}
else if ($("input:checkbox:checked").length == 0) {
// do something else
}
alert($("input[name=sports]:checked").length);
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.
精彩评论