Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if at least one checkbox is checked using jQuery

I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?

<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
like image 201
Kate Wintz Avatar asked Dec 03 '11 18:12

Kate Wintz


4 Answers

This should do the trick:

function isOneChecked() {
    return ($('[name="service[]"]:checked').length > 0);
}
like image 89
jabclab Avatar answered Oct 23 '22 08:10

jabclab


var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;
like image 35
Zain Khan Avatar answered Sep 19 '22 18:09

Zain Khan


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;
});
like image 17
Andy E Avatar answered Oct 23 '22 08:10

Andy E


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.

like image 16
Brandon Gano Avatar answered Oct 23 '22 10:10

Brandon Gano