148

I'm having trouble figuring this out. I have two checkboxes (in the future will have more):

  • checkSurfaceEnvironment-1
  • checkSurfaceEnvironment-2

Basically, I want to write an if statement and test if one of them is checked and another is NOT checked. What's the easiest way to accomplish the following:

if ( $("#checkSurfaceEnvironment-1").attr('checked', true) &&
     $("#checkSurfaceEnvironment-2").is('**(NOT??)** :checked') ) {
        // do something
}
1
  • 3
    Use || not && to check if either is checked. && checks if both are checked. Commented Jul 11, 2012 at 19:41

19 Answers 19

266

One reliable way I use is:

if($("#checkSurfaceEnvironment-1").prop('checked') == true){
    //do something
}

If you want to iterate over checked elements use the parent element

$("#parentId").find("checkbox").each(function(){
    if ($(this).prop('checked')==true){ 
        //do something
    }
});

More info:

This works well because all checkboxes have a property checked which stores the actual state of the checkbox. If you wish you can inspect the page and try to check and uncheck a checkbox, and you will notice the attribute "checked" (if present) will remain the same. This attribute only represents the initial state of the checkbox, and not the current state. The current state is stored in the property checked of the dom element for that checkbox.

See Properties and Attributes in HTML

Sign up to request clarification or add additional context in comments.

6 Comments

Umm... this will just set checked = true
@Pablo - Check my answer below, which I is also a reliable/apt option.
@PabloMescher Hey, can you please help me? I actually want to determine which checkbox(es) is/are checked among several? And, enable/disable textbox next to it. Any help will be highly appreciated.
@1lastBr3ath sure, if you are using jQuery you just have to find a selector for the textbox relative to the checkbox and use my second example. It would look something like if($(this).prop('checked')) { $(this).find("<textboxSelector>").attr("disabled", true); }
@Stophface in this case this property will always be a boolean since it is a computed property and not a string, so you can get away with using ==. It is wise to always use === though since this is not always the case
|
104
if (!$("#checkSurfaceEnvironment-1").is(":checked")) {
    // do something if the checkbox is NOT checked
}

Comments

34

You can also use either jQuery .not() method or :not() selector:

if ($('#checkSurfaceEnvironment').not(':checked').length) {
    // do stuff for not selected
}

JSFiddle Example


Additional Notes

From the jQuery API documentation for the :not() selector:

The .not() method will end up providing you with more readable selections than pushing complex selectors or variables into a :not() selector filter. In most cases, it is a better choice.

1 Comment

!$("#checkSurfaceEnvironment").is(":checked") returns a boolean. It is true if the checkbox is not checked. $('#checkSurfaceEnvironment').not(':checked') returns an array of DOM elements. Testing this with 'if' returns 'true' even if there was no match to the selector and the array is empty. The only way your answer could be correct is if you tested i$('#checkSurfaceEnvironment').not(':checked').length, which will return 0 or 1.
24

An alternative way:

Here is a working example and here is the code, you should also use prop.

$('input[type="checkbox"]').mouseenter(function() { 
    if ($(this).is(':checked')) {
        //$(this).prop('checked',false);
        alert("is checked");
    } else {
         //$(this).prop('checked',true);
        alert("not checked");
    }
});​

I commented out the way to toggle the checked attribute.

Comments

21

I think the easiest way (with jQuery) to check if checkbox is checked or NOT is:

if 'checked':

if ($(this).is(':checked')) {
// I'm checked let's do something
}

if NOT 'checked':

if (!$(this).is(':checked')) {
// I'm NOT checked let's do something
}

1 Comment

Pretty simple question deserves a quite simple answer. He simply asked how you check if a box is NOT checked, while most of the answers here are to check if it IS checked. Thanks for keeping it simple.
11
if ( $("#checkSurfaceEnvironment-1").is(":checked") && $("#checkSurfaceEnvironment-2").not(":checked") )

1 Comment

The .is(":checked") works great, the .not(":checked") does not work for me
6

I was looking for a more direct implementation like avijendr suggested.

I had a little trouble with his/her syntax, but I got this to work:

if ($('.user-forms input[id*="chkPrint"]:not(:checked)').length > 0)

In my case, I had a table with a class user-forms, and I was checking if any of the checkboxes that had the string checkPrint in their id were unchecked.

Comments

4

Here I have a snippet for this question.

$(function(){
   $("#buttoncheck").click(function(){
        if($('[type="checkbox"]').is(":checked")){
            $('.checkboxStatus').html("Congratulations! "+$('[type="checkbox"]:checked').length+" checkbox checked");
        }else{
            $('.checkboxStatus').html("Sorry! Checkbox is not checked");
         }
         return false;
   })
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <p>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0">
      Checkbox</label>
    <br>
    <label>
      <input type="checkbox" name="CheckboxGroup1_" value="checkbox" id="CheckboxGroup1_1">
      Checkbox</label>
    <br>
  </p>
  <p>
    <input type="reset" value="Reset">
    <input type="submit" id="buttoncheck" value="Check">
  </p>
  <p class="checkboxStatus"></p>
</form>

Comments

3

To do it with .attr() like you have, to see if it's checked it would be .attr("checked", "checked"), and if it isn't it would be .attr("checked") == undefined

Comments

1

Return true if all checbox are checked in a div

function all_checked (id_div){
 all_checked = true;

 $(id_div+' input[type="checkbox"]').each(function() { 
    all_checked = all_checked && $('this').prop('checked');
 }

 return all_checked;
}

Comments

1

Simple and easy to check or unchecked condition

<input type="checkbox" id="ev-click" name="" value="" >

<script>
    $( "#ev-click" ).click(function() {
        if(this.checked){
            alert('checked');
        }
        if(!this.checked){
            alert('Unchecked');
        }
    });
</script>

Comments

1

try this one

if ($("#checkSurfaceEnvironment-1:checked").length>0) {
    //your code in case of NOT checked
}

In Above code selecting the element by Id (#checkSurfaceEnvironment-1) then filter out it's checked state by (:checked) filter.

It will return array of checked element object. If there any object exists in the array then if condition will be satisfied.

1 Comment

Although your answer might help, you should at least explain why. As it is, your answer has been passed into the Low Quality Posts moderation queue (which is where I am viewing it) I suggest you edit your answer to add an explanation.
1

There are two way you can check condition.

if ($("#checkSurfaceEnvironment-1").is(":checked")) {
    // Put your code here if checkbox is checked
}

OR you can use this one also

if($("#checkSurfaceEnvironment-1").prop('checked') == true){
    // Put your code here if checkbox is checked
}

I hope this is useful for you.

Comments

1

Here is the simplest way given

 <script type="text/javascript">

        $(document).ready(function () {
            $("#chk_selall").change("click", function () {

                if (this.checked)
                {
                    //do something
                }
                if (!this.checked)
                {
                    //do something

                }

            });

        });

    </script>

Comments

0

I used this and in worked for me!

$("checkbox selector").click(function() {
    if($(this).prop('checked')==true){
       do what you need!
    }
});

Comments

0

I know this has already been answered, but still, this is a good way to do it:

if ($("#checkbox").is(":checked")==false) {
    //Do stuff here like: $(".span").html("<span>Lorem</span>");
}

Comments

0
if($("#checkbox1").prop('checked') == false){
    alert('checkbox is not checked');
    //do something
}
else
{ 
    alert('checkbox is checked');
}

1 Comment

While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
0
var getVal=$('#checkbox_id').is(":checked"); // jQuery

var getVal=document.getElementById("checkbox_id").checked //JavaScript

if (getVal==true) {
// perform task
} else {
// perform task
}

1 Comment

Please don't post code-only answers. The main audience, future readers, will be grateful to see explained why this answers the question instead of having to infer it from the code. Also, since this is an old, well answered question, please explain how it complements all other answers.
-4
$("#chkFruits_0,#chkFruits_1,#chkFruits_2,#chkFruits_3,#chkFruits_4").change(function () {
        var item = $("#chkFruits_0,#chkFruits_1,#chkFruits_2,#chkFruits_3,#chkFruits_4");
    if (item.is(":checked")==true) {
        //execute your code here
    }

    else if (item.is(":not(:checked)"))
    {
        //execute your code here
    }

});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.