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[]">
Felix Loether
  • 6,010
  • 2
  • 32
  • 23
Kate Wintz
  • 633
  • 2
  • 11
  • 24

10 Answers10

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;
});
Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445
17

This should do the trick:

function isOneChecked() {
    return ($('[name="service[]"]:checked').length > 0);
}
pkatukam
  • 33
  • 5
jabclab
  • 14,786
  • 5
  • 54
  • 51
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.

Brandon Gano
  • 6,430
  • 1
  • 25
  • 25
  • 3
    If I see `$(this).is(':checked')`, I take the developer out back and have some words with him. – Raynos Dec 04 '11 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. – Aron Rotteveel Dec 04 '11 at 14:11
  • @Aron: (1) Unnecessary use of `.each`. (2) Unnecessary use of `$(this).is(':checked')`. `this.checked` would work just as well. (3) `$("input[name=service[]]:checked")` would get you the list of checked boxes without even having to go through all this crap. Get the length, and you're done. Take your pick. – cHao Dec 04 '11 at 16:27
  • 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. – Aron Rotteveel Dec 04 '11 at 17:04
  • Bad code should -- and will -- be called out as such. This being a site for people to learn stuff, i wouldn't want some poor newbie to look at this and think it's the way to do things. Fun part is, i haven't even downvoted (yet) -- i was just explaining why i would. The code betrays a misunderstanding of fundamentals. – cHao Dec 04 '11 at 19:48
  • @AronRotteveel we down vote answers that promote bad code. It's the same as down voting a C answer that's correct but uses `goto` – Raynos Dec 04 '11 at 23:37
  • @Aron: I feel this is somewhat my fault, as I brought up this question as a topic for discussion in [JavaScript chat](http://chat.stackoverflow.com/rooms/17/javascript). However, it is quite common to down vote an answer, especially if accepted, when it is a bad solution. This lets other visitors interested in solving the same problem see that the community disagrees with the accepted approach, and encourages them to scroll down for better answers (of which there are several here). Down votes aren't personal or malicious, and should not be seen as such. They're actually a very useful tool. – Andy E Dec 05 '11 at 08:40
  • 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. – Brandon Gano Dec 05 '11 at 09: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. – Tim Post Sep 13 '12 at 06:04
  • For my case, this is working only the first time after refresh page. After that it is not. Anyone knows why that way? – Anu Sep 05 '19 at 07:12
  • @Anu, I'd need to see your code, as there are too many things that could cause this. Can you post a new questions and link to it here? – Brandon Gano Sep 06 '19 at 10:37
  • @BrandonGano I code the following way and able to get the job done `if(jQuery('#main input[type=checkbox]:checked').length) { checked = true; }` After that just check the variable `if(!checked){ do something }` – Anu Sep 09 '19 at 02:34
3

Another answer:

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

or

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

It depends on what you want.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
island205
  • 1,730
  • 17
  • 28
  • You could totally `:checkbox:checked` it up – Raynos Dec 04 '11 at 14:09
  • @island205: What do you mean by "misunderstand css selector"? – BoltClock Dec 04 '11 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 05 '11 at 01: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 05 '11 at 04:17
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

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;      

            });
vaibhav kulkarni
  • 1,733
  • 14
  • 20
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">
Antonio Ooi
  • 1,601
  • 1
  • 18
  • 32
1
var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;
Zain Khan
  • 3,753
  • 3
  • 31
  • 54
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

Raynos
  • 166,823
  • 56
  • 351
  • 396
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
  }
});
Anu
  • 1,123
  • 2
  • 13
  • 42