I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?
<
Edit: The original solution in this answer is inefficient and should not be used. Please see the revised solution based on comments and examples from other answers to this question.
The original (bad) solution follows:
// DO NOT USE; SEE BELOW
$('button').click(function () {
var atLeastOneIsChecked = false;
$('input:checkbox').each(function () {
if ($(this).is(':checked')) {
atLeastOneIsChecked = true;
// Stop .each from processing any more items
return false;
}
});
// Do something with atLeastOneIsChecked
});
The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one. A more efficient solution follows:
$('button').click(function () {
var atLeastOneIsChecked = $('input:checkbox').is(':checked');
// Do something with atLeastOneIsChecked
});
Note that one of the comments indicates a strong dislike for $(this).is(':checked')
. To clarify, there is nothing wrong with is(':checked')
in cases where you are testing a set of objects. That said, calling is(':checked')
on a single item is much less efficient than calling .checked
on the same item. It also involves an unnecessary call to the $ function.
Another answer:
!!$("[type=checkbox]:checked").length
or
!!$("[name=service[]]:checked").length
It depends on what you want.
is()
can do this, and is arguably the only acceptable use of is(":checked")
:
From the jQuery docs, http://api.jquery.com/is/:
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
alert($("input[name='service[]']").is(":checked"));
Example: http://jsfiddle.net/AndyE/bytVX/1/ (based on the fiddle by Brandon Gano)
Alternatively, and potentially faster, you can pass a function to is()
:
$("input[name='service[]']").is(function () {
return this.checked;
});