145

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
}
Xhynk
  • 13,513
  • 8
  • 32
  • 69
user1040259
  • 6,369
  • 13
  • 44
  • 62

19 Answers19

258

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

Community
  • 1
  • 1
Pablo Mescher
  • 26,057
  • 6
  • 30
  • 33
  • 2
    Umm... this will just set `checked = true` – Naftali Jul 11 '12 at 19:40
  • @Pablo - Check my answer below, which I is also a reliable/apt option. – avijendr Oct 30 '13 at 13:11
  • @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 Jun 17 '14 at 10:57
  • @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("").attr("disabled", true); } – Pablo Mescher Jun 17 '14 at 13:03
  • shouldn't you use three `===` to compare with `false`? – four-eyes Oct 27 '16 at 09:12
  • 1
    @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 – Pablo Mescher Oct 27 '16 at 20:42
98
if (!$("#checkSurfaceEnvironment-1").is(":checked")) {
    // do something if the checkbox is NOT checked
}
shweta
  • 8,019
  • 1
  • 40
  • 43
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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
avijendr
  • 3,958
  • 2
  • 31
  • 46
  • 1
    !$("#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. – Thibault Witzig Dec 21 '15 at 18:17
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.

Trufa
  • 39,971
  • 43
  • 126
  • 190
17

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
}
Michael Stachura
  • 1,100
  • 13
  • 18
  • 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. – RationalRabbit Dec 09 '20 at 01:58
11
if ( $("#checkSurfaceEnvironment-1").is(":checked") && $("#checkSurfaceEnvironment-2").not(":checked") )
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
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.

TLama
  • 75,147
  • 17
  • 214
  • 392
MsGirlPerl
  • 337
  • 1
  • 4
  • 11
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>
smci
  • 32,567
  • 20
  • 113
  • 146
Ashok
  • 299
  • 3
  • 8
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

ayyp
  • 6,590
  • 4
  • 33
  • 47
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;
}
Martin Da Rosa
  • 442
  • 4
  • 5
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.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
Satish Kumar sonker
  • 1,250
  • 8
  • 15
  • 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. – Chris Spittles Feb 25 '16 at 09:21
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>
Patrick
  • 12,336
  • 15
  • 73
  • 115
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.

Gaurang Sondagar
  • 814
  • 1
  • 9
  • 23
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>
Debendra Dash
  • 5,334
  • 46
  • 38
0

I used this and in worked for me!

$("checkbox selector").click(function() {
    if($(this).prop('checked')==true){
       do what you need!
    }
});
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>");
}
Hello World
  • 35
  • 11
0
if($("#checkbox1").prop('checked') == false){
    alert('checkbox is not checked');
    //do something
}
else
{ 
    alert('checkbox is checked');
}
  • 4
    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](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer - [From Review](https://stackoverflow.com/review/low-quality-posts/21386940) – Nick Nov 12 '18 at 10:17
0
var getVal=$('#checkbox_id').is(":checked"); // jQuery

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

if (getVal==true) {
// perform task
} else {
// perform task
}
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
  • 1
    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. – Gert Arnold Dec 16 '22 at 21:52
-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
    }

});
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880