0

I've tried searching the site, but am really struggling to find what I want... Basically I have some jQuery code that checks the state of three IDs, they are tied to three checkboxes;

$('#submitButton').click(function(){
    if($("#cb1,#cb2,#cb3").is(':checked'))
        return true;
    else
        return false;
});

How would I restructure this jQuery statement to make it so that all three checkboxes have to be CHECKED? At the moment, either one can be checked for the action to be performed

I'm betting there is a really simple solution to all of this, but I have been lpooking at it for so long, I just can't see it. Could someone with a fresh pair of eyes and a less addled brain please steer me in the right direction?

3
  • Felix fixed it. Thank matey, here a FIDDLE of the working code for anyone else who might require it ;) JSFiddle Commented Feb 20, 2014 at 14:24
  • Please check this: jsfiddle.net/mahavir4dev/Z93Y5 This will work for any number of checkboxes. Commented Feb 20, 2014 at 14:25
  • Many thanks my friend, that is immensely helpful ;) Commented Feb 20, 2014 at 14:46

6 Answers 6

1

You need to use:

$('#submitButton').click(function(){
    if ($('#cb1').is(':checked') && $('#cb1').is(':checked') && $('#cb3').is(':checked')) {
        return true;
    } else {
        return false;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Ace!! You sir are a legend. Forgive my stupidity, but what does the && mean?
@Daren && in javascript means Logical AND. You can read more on the logical operators here. Glad it helped :)
0

Use

if($("#cb1").is(':checked') && $("#cb2").is(':checked') && $("#cb3").is(':checked'))

$("#cb1,#cb2,#cb3").is(':checked') will return result for the 1st element only

Comments

0

Try:

$('#submitButton').click(function(){
    if($("#cb1:checked,#cb2:checked,#cb3:checked").length === 3)
        return true;
    else
        return false;
});

Comments

0

You can use:

 if ($('#cb1:checked,#cb2:checked,#cb3:checked').length == 3) {
   //all three are checked.do something
 }

or

 if ($('#cb1:checked,#cb2:checked,#cb3:checked').length == $('#cb1,#cb2,#cb3').length) {
   //all three are checked.do something
 }

Comments

0

You could try:

$('#submitButton').click(function(){
    if($('#cb1')[0].checked && $('#cb2')[0].checked && $('#cb3')[0].checked)return true;
    return false;
});

Comments

0

You can just add a class to your checkboxes and use like so:

$('#submitButton').click(function(){
    if($(".myCheckbox:checked").length == 3) {
        console.log('true');
    }
    else {
        console.log('false');
    }
});

Here is the JSFiddle Example:

http://jsfiddle.net/cLH8s/1/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.