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.