ChatGPT解决这个技术问题 Extra ChatGPT

jQuery: Test if checkbox is NOT checked

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
}
Use || not && to check if either is checked. && checks if both are checked.

C
Community

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


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("").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
s
shweta
if (!$("#checkSurfaceEnvironment-1").is(":checked")) {
    // do something if the checkbox is NOT checked
}

i
informatik01

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.


!$("#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.
T
Trufa

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.


M
Michael Stachura

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
}

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.
Z
Zoltan Toth
if ( $("#checkSurfaceEnvironment-1").is(":checked") && $("#checkSurfaceEnvironment-2").not(":checked") )

T
TLama

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.


s
smci

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




a
ayyp

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


M
Martin Da Rosa

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

P
Patrick

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>

M
MD. Khairul Basar

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.


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.
G
Gaurang Sondagar

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.


D
Debendra Dash

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>

S
Seyed Mohammad Hosseini

I used this and in worked for me!

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

H
Hello World

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

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

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
B
Bill the Lizard
$("#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
    }

});