Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

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

How do I successfully query the checked property?

share|improve this question
22  
This is the best thread on stackoverflow – fatmatto Dec 7 '11 at 11:32
1  
~ 1/4 of Jon Winstanley's reputation came from his comment here. Bravo, you deserve it :) – Leo Jweda Mar 1 '12 at 5:44
3  
$('#isAgeSelected').is(':checked') – Andrei Tchijov Aug 25 '12 at 17:04
add comment (requires an account with 50 reputation)

27 Answers

Try this:

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

You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:

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

EDIT (14 months later): 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

share|improve this answer
5  
i have tried the above condition too, but it returns false only – Prasad May 23 '09 at 15:24
7  
$("#txtAge").toggle(this.checked); Does exactly the same as $("#txtAge").toggle(). So, if for some reason the state is checked and the next div is hidden (you clicked back button in your browser) - it won't work as expected. – Maksim Vi. Oct 4 '10 at 20:55
7  
The top answer here is much cleaner and intuitive than all this is(':checked') business. :) – Chiramisu Mar 5 '12 at 19:11
2  
@Chiramisu - If you had read the answer all the way down, you would have noticed that my edit does not use the is(':checked') business. – karim79 Mar 6 '12 at 10:14
79  
+1 for the follow-up...I hate it when answers get stale – Roly Jun 1 '12 at 19:52
show 7 more commentsadd comment (requires an account with 50 reputation)

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}
share|improve this answer
alert($('input[name=isAgeSelected]').attr('checked')); The above code shows true/false based on the check. Any problem with the previous tries – Prasad May 23 '09 at 15:41
Prasad, are you referencing your checkbox by name or ID? I'm getting confused now... – karim79 May 23 '09 at 15:52
i have referenced it by name – Prasad May 23 '09 at 16:08
Can you not give it an ID? Things would be a lot easier, In your example you have address it by it's ID – xenon May 23 '09 at 16:10
add comment (requires an account with 50 reputation)
up vote 27 down vote accepted

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

share
locked by George Stocker Jul 30 '12 at 15:47
15  
Are you not missing a #? – teedyay Aug 11 '10 at 13:12
59  
"== true" is a bit redundant. – Steve Bennett Mar 8 '11 at 0:44
7  
@jcollum: Equality comparisons with booleans on one side and constants on the other is a classic anti-pattern, and I'd have pointed out the same. – Adam Robinson Apr 18 '11 at 18:17
24  
Why is this answer accepted? It's not even valid. ( Oh, because the OP has accpeted his own anser! ) I think he's trying to say $.get('#isAgeSelected')... – Nick Perkins Jun 2 '11 at 19:57
37  
This question is tagged jquery, but the accepted answer is requires MicrosoftAjax.js. Misleading. – Charlie Kilian Aug 25 '11 at 17:19
show 5 more commentscomments disabled on deleted / locked posts / reviews

This post has been locked due to the high amount of off-topic comments generated. For extended discussions, please use chat.

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.

share|improve this answer
38  
The ==true operation is unnecessary, if does this anyway. – peterjwest Jan 14 '11 at 10:23
Good answer, votes for you. – MrBoJangles Jul 20 '11 at 23:31
This works because $("#checkkBoxId").attr("checked") returns "checked" or "" (empty string). And an empty string is falsy, non-empty string is truthy, see about truthy/falsy values docs.nodejitsu.com/articles/javascript-conventions/… – Adrien Be Jul 12 at 7:09
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

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.

share|improve this answer
Bingo. Question asker's comments identify that this is the correct solution to his problem (even if not the correct solution according to the question he originally asked): he is using an HTML form generator that is not correctly associating control IDs with the controls themselves (but, presumably, with an element that contains both the control and associated elements, e.g. labels). – Jules Apr 5 '12 at 12:18
add comment (requires an account with 50 reputation)

this works for me,

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
share|improve this answer
add comment (requires an account with 50 reputation)

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)

share|improve this answer
add comment (requires an account with 50 reputation)

Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked
share|improve this answer
2  
+1 This Works great :) – IT ppl Apr 26 '12 at 7:39
add comment (requires an account with 50 reputation)

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
}
share|improve this answer
add comment (requires an account with 50 reputation)

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

});
share|improve this answer
add comment (requires an account with 50 reputation)

My way of doing this is:

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

    alert("checkbox is checked");

} else {

    alert("checkbox is not checked");

}
share|improve this answer
Not sure why this was downvoted. A valid, albeit unusual way to check for a checkbox being checked. – Jules Apr 5 '12 at 12:15
add comment (requires an account with 50 reputation)

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);
});
share|improve this answer
add comment (requires an account with 50 reputation)
$(selector).attr('checked') !== undefined

This returns true if the input is checked and false if it is not.

share|improve this answer
4  
I understand why this might work in certain scenarios, although it has the same issue as .attr('checked') in that it doesn't always return the correct state. As per Salman A's answer (and perhaps others'), it's a safer option to make use of .prop('checked') instead. Besides, it's also possible to declare undefined as var undefined = 'checked';. – Wynand Apr 5 at 0:56
.prop('checked') does seem a better answer now. It wasn't as reliable at the time it was written. I do not understand, nor do think it is a good idead to redeclare undefined. – fe_lix_ Apr 25 at 10:02
add comment (requires an account with 50 reputation)
if ($("#checkkBoxId").is(':checked') == true) {
                alert("Checked");
            }
            else {
                alert("Unchecked");
            }
share|improve this answer
5  
-1: Exact the same has already been posted by Bhanu Krishnan last year – Marc Mar 20 '12 at 5:53
2  
if (condition == true) { ... }, why would you do that? Double-equals comparison will implicitly cast the condition to a boolean anyway, so that is pointless. In most cases you would just do if (condition) { ... }. If you really need to check that the condition is exactly true and not just something truthy, then you'd use triple equals like if (condition === true) { ... }. But == true is just pointless. – Ben Lee Dec 18 '12 at 21:06
add comment (requires an account with 50 reputation)

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.

share|improve this answer
Well, .hidden is not very cross-browser, although I like this solution :) – Florian Margaine Mar 20 '12 at 19:59
Thanks @FlorianMargaine, I learned something new. I've addressed the cross-browser compatibility issue. – Octavian Damiean Mar 20 '12 at 20:38
It is indeed the best way to use style. That is unfortunate though, as .hidden performance is way better. – Florian Margaine Mar 21 '12 at 9:37
Assignment inside a conditional operator? Legal, yes. Not what I'd call good style, however. – Jules Apr 5 '12 at 12:12
@Jules Thanks to Raynos I understood what you mean. He has changed the display property example and I've changed the hidden property example. – Octavian Damiean Apr 5 '12 at 15:51
show 1 more commentadd comment (requires an account with 50 reputation)

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")
share|improve this answer
1  
for some reason, prop("checked") worked for me, but not is(':checked') – BraveNewMath Jun 11 '12 at 20:19
add comment (requires an account with 50 reputation)

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.

share|improve this answer
2  
your answer would be much better with a brief explanation. – Anup Cowkur Dec 10 '12 at 5:26
add comment (requires an account with 50 reputation)
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}
share|improve this answer
add comment (requires an account with 50 reputation)
if( undefined == $('#isAgeSelected').attr('checked') ) {
$("#txtAge").hide();
} else {
$("#txtAge").show();
}`adfdadgagdah`
share|improve this answer
add comment (requires an account with 50 reputation)
$(this).toggle($("input:checkbox", $(this))[0].checked);

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

share|improve this answer
add comment (requires an account with 50 reputation)

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");
        }
});
share|improve this answer
add comment (requires an account with 50 reputation)

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

enter image description here

share|improve this answer
add comment (requires an account with 50 reputation)

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')

share|improve this answer
add comment (requires an account with 50 reputation)
if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

or

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}
share|improve this answer
add comment (requires an account with 50 reputation)

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

share|improve this answer
add comment (requires an account with 50 reputation)

There are several ways of doing it: .is()

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

or you can try: .prop()

$("#checkkBoxId").prop('checked') 
share|improve this answer
add comment (requires an account with 50 reputation)

protected by Mr. Alien May 21 at 16:47

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.