11

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[]">

10 Answers 10

17

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;
});
17

This should do the trick:

function isOneChecked() {
    return ($('[name="service[]"]:checked').length > 0);
}
16

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.

12
  • 3
    If I see $(this).is(':checked'), I take the developer out back and have some words with him.
    – Raynos
    Dec 4, 2011 at 13:56
  • 2
    Why is this answer so massively downvoted? If anything is wrong with it, please provide a reason as to why this is the case in the comments. Dec 4, 2011 at 14:11
  • 9
    Obviously, the code can be written a lot cleaner. That does not, however, make this answer incorrect. This downvoting behaviour is ridiculous and is demotivational. Downvoting a 'not-so-good' answer without explanation has no point at all. Dec 4, 2011 at 17:04
  • 1
    @Andy E: I couldn't agree more. I fully support down-votes in cases where the accepted answer is not the best solution. I've updated the answer to summaries the issues with the original solution and offer a better one. Dec 5, 2011 at 9:12
  • 1
    This is actually a fine answer, because it works through a sub optimal approach that others would be likely to try, explains why it's bad and then explains a more proper solution. Good on you for leaving it around.
    – user50049
    Sep 13, 2012 at 6:04
3

Another answer:

!!$("[type=checkbox]:checked").length

or

!!$("[name=service[]]:checked").length

It depends on what you want.

4
  • You could totally :checkbox:checked it up
    – Raynos
    Dec 4, 2011 at 14:09
  • @island205: What do you mean by "misunderstand css selector"?
    – BoltClock
    Dec 4, 2011 at 17:29
  • @BoltClock,let me see.[1]one day,there is newcomer asked "why i can't get textarea width $(':text,:textarea')?" in JS chat room,i consider that it is easy misunderstanded by newcomer.[2]is ":checkbox" a css selector? no,it is a bad standard just in jQuery.in css,":something" is pseudo- classes.[3]"[type=checkbox]" is more efficient, $ can use "querySelectorAll" API provided by browser.BTW,give me a upvote please,that i can downvote the wrong but selected answer!
    – island205
    Dec 5, 2011 at 1:58
  • I don't get it. The whole point of jQuery's selector engine is to let you use advanced CSS selectors in older browsers, and certain non-standard selectors/extensions to simplify your selection code. If you're avoiding it just for performance you may as well use QSA directly without going through the $() call and not teach anybody about jQuery.
    – BoltClock
    Dec 5, 2011 at 4:17
1
var checkboxes = document.getElementsByName("service[]");
if ([].some.call(checkboxes, function () { return this.checked; })) {
  // code
}

What you want is simple, get all the elements with the name, then run some code if some of those elements are checked.

No need for jQuery.

You may need an ES5 shim for legacy browsers though

1

You should try like this....

var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");

checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));

});

1
  • It would be better if you could also explain why.
    – Ben
    Dec 3, 2012 at 23:26
1

you need to check if checkbox is checked or not.

$("#select_all").click(function(){
           var checkboxes = $("input[type='checkbox']");
           if(checkboxes.is(":checked"))
               alert("checked");
           else
               alert("select at least one;      

            });
1
var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;
2
  • 3
    checkbox.length would tell you how many checkboxes have that name. It doesn't discriminate between checked and unchecked boxes.
    – cHao
    Dec 4, 2011 at 10:59
  • Updated the answer
    – Zain Khan
    Aug 17, 2016 at 13:29
1

The square bracket [] is not necessary:

var atLeastOneIsChecked = $("input[name='service']:checked").length > 0;

The same goes to your HTML, but better to have an id to uniquely identify each of the checkboxes:

<input id="chk1" type="checkbox" name="service">
<br />
<input id="chk2" type="checkbox" name="service">
<br />
<input id="chk3" type="checkbox" name="service">
<br />
<input id="chk4" type="checkbox" name="service">
<br />
<input id="chk5" type="checkbox" name="service">
0

You can do the following way. Initially set a variable, lets say checked as false. Then set it to true if the following condition met. Use an if statement to check the variable. Take note: Here submit is the id of the button, main is the id of the form.

$("#submit").click(function() {
  var checked = false;
  if (jQuery('#main input[type=checkbox]:checked').length) {
    checked = true;
  }
  if (!checked) {
    //Do something
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.