Check checkbox checked property using jQuery
2
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

How do I successfully query the checked property?
improve this question | comment
Kayleigh Beer Created at: 2013-11-13 17:07:29 UTC By Kayleigh Beer
This is the best thread on stackoverflow - Emanuel Heathcote
~ 1/4 of Jon Winstanley's reputation came from his comment here. Bravo, you deserve it :) - Trycia Eichmann
$('#isAgeSelected').is(':checked') - Dr. Efrain Lowe
30 Answers
0
<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad

$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    //do some other action
  }

})


this can help if you want that the required action has to be done only when you check the box not at the time you remove the check
0
My way of doing this is:

if ( $("#checkbox:checked").length ) {

    alert("checkbox is checked");

} else {

    alert("checkbox is not checked");

}

0
this works for me,

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

0
I verified in Firefox 9.0.1 that the following works for catching the state of a checkbox post change:

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});

0
If you are using an updated version of jquery, you must go for .prop method to resolve your issue:

$('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. So do as given below.

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}


Hope it helps someone.. :)- Thanks.
0
I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};


First you get both elements by their ID. Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.

Here is a fiddle for you to test it.

Addendum

If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.

elem.style.display = this.checked ? 'inline' : 'none';


Slower but cross-browser compatible.
0
I am using this and this is working absolutely fine:

if($("#checkkBoxId").attr("checked")==true)
{
    alert("Checked");
}
else
{
    alert("Unchecked");
}


Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.
0
This worked for me:

$get("isAgeSelected ").checked == true


Where isAgeSelected is the id of the control.

Also, @karim79's answer works fine. I am not sure what I missed at the time I tested it.

Note, this is answer uses Microsoft Ajax, not jQuery
0
Since jQuery 1.6, The behavior of jQuery.attr() has changed and users are encouraged  not to use it to retrieve an element's checked state. Instead, you should use jQuery.prop():

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // for checked attribute it returns true/false;
                                        // return value changes with checkbox state
);                           


Two other possibilities are:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

0
Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself! Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed(independent of how it's done so).

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();

});

0
$(selector).attr('checked') !== undefined


This returns true if the input is checked and false if it is not.
0
Please consider that the best cross-browser & cross-HTML version way to check if a check box is checked or not is:

$("#checkkBoxId").is(':checked') 


or

$("#checkkBoxId").prop('checked') 


Other ways may working on some browsers but not all browsers and also HTML version is effecting on their behavior.

So the only 100% working way is using .is(':checked') or .prop('checked')
0
Top answer didn't do it for me, this did though:

<script type="text/javascript">
$(document).ready(function(){

    $("#li_13").click(function(){
        if($("#agree").attr('checked')){
            $("#saveForm").fadeIn();
        }

        else
        {
            $("#saveForm").fadeOut();
        }
    });
    });

</script>


UPDATE 20121213: Basically when the element #li_13 is clicked, it checks if the element #agree (which is the checkbox) is checked by using the .attr('checked') function, if it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.
0
I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

0
I ran in to the exact same issue. I have an ASP.NET checkbox

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />


In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }


I'm sure you can also use the ID instead of the CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }


I hope this helps you.
0
if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}


or

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}

0
There's a much prettier way to do this, using toggle:

$('#isAgeSelected').click(function () {
    $("#txtAge").toggle(this.checked);
});

<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>​


Fiddle Demo
0
Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

0
Using jQuery > 1.6 

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true


Using the new property method:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}

0
I was having the same problem and none of the posted solutions seemed to work and then I found out that it's because ASP.NET renders the CheckBox control as a SPAN with INPUT inside, so the CheckBox ID is actually an ID of a SPAN, not an INPUT, so you should use:

$('#isAgeSelected input')


rather than

$('#isAgeSelected')


and then all methods listed above should work.
0
Here's an example that includes initialising the show/hide to match the state of the checkbox when the page loads; taking account of the fact that firefox remembers the state of checkboxes when you refresh the page, but won't remember the state of the shown/hidden elements.

$(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});


(with help from other answers on this question)
0
I am using this :

 <input type="checkbox" id="isAgeSelected" value="1" /> <br />
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide(); 

0
Include jQuery from local file system. I used Google CDN there are also many CDNs to choose.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


The code will execute as soon as checkbox inside mycheck class is clicked. If the current clicked checkbox is checked then it will disable all other and enable the current one. If current one is unchecked, it will again enable all checkboxes for re checking.

<script type="text/javascript">
$(document).ready(function() {

    var checkbox_selector = '.mycheck input[type=checkbox]';

    $(checkbox_selector).click(function() {
        if ($($(this)).is(':checked')) {
            // disable all checkbox
            $(checkbox_selector).attr('disabled', 'disabled');
            // enable current one
            $($(this)).removeAttr('disabled');
        } else {
            // if unchecked open all checkbox
            $(checkbox_selector).removeAttr('disabled');
        }
    });
});
</script>


Simple form to test

<form method="post" action="">
    <div class="mycheck">
        <input type="checkbox" value="1" /> Television 
        <input type="checkbox" value="2" /> Computer 
        <input type="checkbox" value="3" /> Laptop 
        <input type="checkbox" value="4" /> Camera 
        <input type="checkbox" value="5" /> Music Systems 
    </div>
</form>


Output Screen


0
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

0
if( undefined == $('#isAgeSelected').attr('checked') ) {
$("#txtAge").hide();
} else {
$("#txtAge").show();
}`adfdadgagdah`

0
$(this).toggle($("input:checkbox", $(this))[0].checked);


When you are selecting out of context, remember you need the [0] to access the checkbox
0
This was my workaround

$('#vcGoButton').click(function (){
    var buttonStatus=$('#vcChangeLocation').prop('checked');
    console.log("status is " + buttonStatus);
    if(buttonStatus){
        var address=$('#vcNewLocation').val();
        var cabNumber=$('#vcVehicleNumber').val();
        $.get('postCabLocation.php',
            {address: address, cabNumber: cabNumber},
            function(data) {
                console.log("changed vehicle " + cabNumber + " location to " + address );
            });
        }else{
            console.log("vc go button clicked but no location action");
        }
});

0
The checked attribute of an input type="checkbox" is mapped with the defaultChecked property, not with the checked property. 

So when doing something in a page when a checkbox is checked on uncheked, use the prop() method instead. It fetches the property value and changes as the state of the checkbox changes. 

Using attr() or getAttribute(in pure js) in these cases are not the proper way of doing things. 

if elem is the concerned checkbox then do something like this to fetch the value:

elem.checked


or

$(elem).prop('checked')

0
forgive me if there are previous posted versions of this above but I wanted to post the a minimal amount of code I think needed to do something like this effectively.  I found this method to be useful, it returns an array of the check boxes that are checked and then you can use their value.  (This solution uses jQuery)

 //this is how you get them  
    var output = "";
    var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
                        if(checkedBoxes.length <= 0) {
                            alert('Please select check boxes');
                            return false;
                        };
 //and how is how you use them
                        checkedBoxes.each(function() {
                            output +=  this.value + ", ";
                        };


printing "output" will give you a comma separated list of your values
0
There are several ways of doing it:
.is()

$("#checkkBoxId").is(':checked') 


or you can try:
.prop()

$("#checkkBoxId").prop('checked') 

Your Answer