How to check whether a checkbox is checked in jQuery?

4 058

610

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?

Prasad

Posted 2009-05-23T15:16:39.917

Reputation: 26 035

Check some other ways to do this using jQuery here http://stackoverflow.com/a/22019103/1868660

– Subodh Ghulaxe – 2014-02-25T15:45:46.880

$('#isAgeSelected').change(function(){ alert($('#chkSelect').attr('checked')); }); – Khaled.K – 2014-05-14T05:43:47.077

It's important to note everyone, that there is a colon between the opening single quote and the word "checked." It represents a pseudoclass selector of the checkbox. I just made the mistake of not copying and pasting the code and missed the colon. Frustrating. – OKGimmeMoney – 2014-08-15T15:16:34.293

10$('#isAgeSelected') returns collection, replace it with: $('#isAgeSelected')[0].checked – zamoldar – 2015-05-19T16:53:21.837

For properties, use .prop(). .attr() is for attributes. – Joseph Lennox – 2015-06-12T02:16:27.710

13why not $('#isAgeSelected').checked – mmcrae – 2015-10-27T14:52:34.120

Starting jquery 1.6 there have been significant changes the way attributes and properties are dealt with. For your case following should work: if($('#isAgeSelected').prop("checked")) { $("#txtAge").show(); } else { $("#txtAge").hide(); }

The condition in if statement will simply return true or false depending upon the checked/unchecked state of the check box. For more details refer to attributes vs. properties section on this link.

– RBT – 2016-02-12T18:44:57.453

For a comprehensive ( and correct ) answer see: http://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery/426276#426276

– Paul Kenjora – 2016-04-19T14:11:12.583

9Since jQuery selectors return array, you can use $('#isAgeSelected')[0].checked – Felipe Leão – 2016-06-20T19:36:34.553

for me the following tweak worked: replace .attr('checked') with .is(':checked') – Mark N Hopgood – 2018-05-11T09:42:40.507

This is evidens of extraterrestrial aliens – Erik – 2018-11-14T09:06:47.093

Answers

90

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

Prasad

Posted 2009-05-23T15:16:39.917

Reputation: 26 035

3 181

How do I successfully query the checked property?

The checked property of a checkbox DOM element will give you the checked state of the element.

Given your existing code, you could therefore do this:

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

However, there's a much prettier way to do this, using toggle:

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

karim79

Posted 2009-05-23T15:16:39.917

Reputation: 292 242

@karim79 i added a textbox , when i checked the checkbox a textbox appeared and i wrote something there and i unchecked the checkbox and again i checked then i am also seeing that text how? an empty text box should come when i am checking checkbox each time, how can i do it? please see here please help

– harry – 2012-02-15T11:05:38.190

19@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 – 2012-03-06T10:14:19.270

@karim79 I know this is old, but his original selector is missing a single quote after the id $('#isAgeSelected).attr which should be $('#isAgeSelected').attr – Mark Schultheiss – 2010-03-26T20:17:13.457

2Please mark the beginning of your answer as the old solution and that there is a better, updated solution later on. Otherwise someone might just visit this page from google, see the first code block, and use it in his project. I know that people should read the whole answer, but that's just the reality of not having infinite amount of time. – duality_ – 2013-09-26T14:05:08.283

I prefer to use $("#txtAge").toggleClass("display-hide"); and &lt;div id="txtAge" class="display-hide"&gt;Age is something&lt;/div&gt;​ instead. But, it's the same idea. Anyway, your answer was helpful. – Gerson – 2014-01-29T21:33:46.337

8to set: $("#chkmyElement")[0].checked = true; to get: if($("#chkmyElement")[0].checked) – JJ_Coder4Hire – 2014-04-22T02:28:35.513

22$("#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. – 2010-10-04T20:55:23.923

2@DCShannon: What do you think this.checked does? – None – 2015-05-17T03:06:51.917

2@squint What I think it might do isn't in the answer. There's some unexplained code that I'm aware will toggle the checkbox regardless of its current state. – DCShannon – 2015-05-18T18:37:34.510

2@DCShannon: Some code is just self explanatory but since this is a Community Wiki, I'll add an explicit explanation. But there are in fact currently words in this answer about checking if the checkbox is check. Those words are this.checked. – None – 2015-05-18T20:18:14.443

according to jquery docs toggle is just to hide and show. – pat capozzi – 2015-05-20T16:30:58.660

1This returns undefined – Elendurwen – 2015-08-03T20:42:45.333

Note that if you want to animate the toggle, simply use the slideToggle animation: $("#txtAge").slideToggle(this.checked); – Etienne Dupuis – 2015-11-20T18:53:08.037

Why just @JJ_Coder4Hire brought up the [0] solution and almost nobody agreed? $('#isAgeSelected')[0].checked works perfectly! – cregox – 2015-11-27T14:51:04.500

I originally had code using toggle but it did not work. If I checked the checkbox and refreshed the page, the checkbox would remain checked but the div would be hidden. Thus toggle would work, but it would show when I unchecked and hide when I checked. I thus had to create a function that would synch the visibility of the div with the status of the checkbox on page load. – dwoodwardgb – 2016-04-24T14:57:56.407

1As with the first commenter, I did not find this an effective solution, perhaps because I am on jQuery 1.11. jQuery recommends using prop("checked") and that worked. – Erica Kane – 2016-05-01T14:27:03.373

34i have tried the above condition too, but it returns false only – Prasad – 2009-05-23T15:24:20.263

Something is amiss. In fact, the code you provided in your question should work. Are you referencing the correct element? – karim79 – 2009-05-23T15:26:59.540

This is the checkbox i am using: <%= Html.CheckBox("isAgeSelected", new { id = "isAgeSelected", onclick = "showAge();" })%>

Also i have checked with alert condition:

alert($('#isAgeSelected').is(':checked'));

but it popups false only – Prasad – 2009-05-23T15:35:16.513

I would try xenon's suggestion, also you might want to test this with a non server-generated checkbox in case it's not being rendered properly. Furthermore, you might want to consider getting rid of the onclick="showAge()" and replace that with a jQuery binding on the click event $('#isAgeSelected').click(function() {... – karim79 – 2009-05-23T15:39:34.220

You may want to stick the line "debugger;" in your code and then step through it. This will allow you to debug it in your browser to see what happens. IE will launch VS, in FireFox it will launch Firebug if installed. Easier if you temporarily make the code more verbose, such as var test = $('#isAgeSelected').is(':checked'); If test...

You could even do var = $('#isAgeSelected') to see if you get the right element and what it's properties are. – Frans – 2009-05-23T17:03:35.663

Note to future editors: The toggle event was deprecated in 1.8 and removed in 1.9. This use of the toggle function remains alive and well. – Heretic Monkey – 2017-05-22T15:45:17.523

16This is not an answer to the question. this.checked is not jQuery, as the OP asked for. Also, it only works when user clicks on the checkbox, which is not part of the question. The question is, again, How to check whether a checkbox is checked in jQuery? at any given time with or without clicking the checkbox and in jQuery. – Marc Compte – 2017-07-06T10:58:14.923

1 611

Use jQuery's is() function:

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

Bhanu Krishnan

Posted 2009-05-23T15:16:39.917

Reputation: 3 503

13If you don't need duration, easing etc., you can use $("#txtAge").toggle($("#isAgeSelected").is(':checked')) – naor – 2013-09-11T07:21:09.980

11

+1 there are different ways to get checked property. Some are listed here

– user3199690 – 2014-10-30T07:07:56.003

@NickG Actually jQuery does have a :visible selector

– hvdd – 2015-07-17T21:37:54.073

2@hvdd I know - I said "property", not selector. – NickG – 2015-07-20T08:16:57.260

@NickG ...I don't understand what you mean. jQuery has no .visible "property" (property? you mean method?) because the no HTML element has a visible property. They have a display style property and it's a bit more complex than on/off. – xDaizu – 2016-01-28T11:43:23.700

@DanielParejoMuñoz I realise that, but once you 'select' them using jQuery, you are not getting the bare DOM element but a JQuery object. So what I meant was: it would be possible for jQuery to easily add a .visible property at that point, reducing all the code required to hide or show something. However I realise now that only certain versions of javascript support properties: http://stackoverflow.com/questions/3208571/create-javascript-property-like-c-sharp-property

– NickG – 2016-01-28T15:54:19.490

@NickG So you mean something like $object.visible(true) as an alias for .show(), and $object.visible(false) for .hide()? – xDaizu – 2016-02-01T08:51:55.870

for some reason this doesn't work for me on chrome. it is fine on ie. I would go with simple document.getElementById like mentioned above. – Vaidas – 2018-01-16T19:18:50.187

does is(':checked') work in IE8? – Rez.Net – 2018-09-19T05:24:21.407

496

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
}

SeanDowney

Posted 2009-05-23T15:16:39.917

Reputation: 9 978

25I would like to know why this is Not the answer ... if you are using jquery at all, then the .prop method is the designed way to check props. .. ... If you are going to do the .is(":checked") approach, that's fine, but it is not the designed way to do it using jquery. right? – dsdsdsdsd – 2013-12-01T12:28:58.843

1@dsdsdsdsd presumably because it needs yet another backwards compatibility step (I'm facing the same issue right now). – user98085 – 2014-01-28T11:38:14.230

17.is(":checked") and .prop("checked") are both valid ways to get the same result in jQuery, .is will work in all versions, .prop requires 1.6+ – gnarf – 2014-06-26T20:50:18.080

If you use .attr('checked') in jQuery 1.11.3, you get undefined, where if you use .prop('checked'), you'll get true/false. I do not see why they changed it to work this way when older browsers cannot support the later jQuery versions that introduced .prop() and therefore need .attr(). The only saving grace is that the older browsers (i.e. IE 8) cannot support anything > jQuery 1.9. Hopefully they did not do this (make .attr('checked') = undefined) in that version! Fortunately, there is always this.checked. – vapcguy – 2015-06-19T16:53:26.090

195

jQuery 1.6+

$('#isAgeSelected').prop('checked')

jQuery 1.5 and below

$('#isAgeSelected').attr('checked')

Any version of jQuery

// Assuming an event handler on a checkbox
if (this.checked)

All credit goes to Xian.

ungalcrys

Posted 2009-05-23T15:16:39.917

Reputation: 3 254

6Technically, this.checked is using straight Javascript. But I love that cross-jQuery-version answer! – vapcguy – 2015-06-19T16:50:35.817

154

I am using this and this is working absolutely fine:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

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

Pradeep

Posted 2009-05-23T15:16:39.917

Reputation: 417

6

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 http://docs.nodejitsu.com/articles/javascript-conventions/what-are-truthy-and-falsy-values

– Adrien Be – 2013-07-12T07:09:07.437

6By jquery 2.1.x it returns always checked if it is checked by default... I don't know whether this behavior is intentional, but it surely does not work ( I guess it is a bug )... The val() does not work either, it stays "on". The prop() is working properly and the dom.checked works either. – inf3rno – 2014-07-23T16:19:57.657

1And the problem comes when you have to support older browsers with .attr()! If only they just left well enough alone.... Found another answer on here said you can just use this.checked for a cross-jQuery solution, since it is just basically Javascript. – vapcguy – 2015-06-19T16:48:48.430

128

Use:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

Lalji Dhameliya

Posted 2009-05-23T15:16:39.917

Reputation: 974

110

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

Salman A

Posted 2009-05-23T15:16:39.917

Reputation: 172 519

4for some reason, prop("checked") worked for me, but not is(':checked') – BraveNewMath – 2012-06-11T20:19:56.130

and $("#txtAge")[0].checked – Yevgeniy Afanasyev – 2018-05-16T03:52:29.357

84

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 :)- Thanks.

Rajesh Omanakuttan

Posted 2009-05-23T15:16:39.917

Reputation: 4 926

why not $('#isAgeSelected').checked ? – mmcrae – 2015-10-27T14:53:21.153

1to use .is you need a colon $('#isAgeSelected').is(':checked') – Patrick – 2016-02-18T12:44:36.663

57

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

arviman

Posted 2009-05-23T15:16:39.917

Reputation: 3 514

3

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

– naor – 2013-09-11T07:02:39.263

51

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.

Octavian Damiean

Posted 2009-05-23T15:16:39.917

Reputation: 35 334

Well, .hidden is not very cross-browser, although I like this solution :) – Florian Margaine – 2012-03-20T19:59:40.947

It is indeed the best way to use style. That is unfortunate though, as .hidden performance is way better.

– Florian Margaine – 2012-03-21T09:37:06.897

Assignment inside a conditional operator? Legal, yes. Not what I'd call good style, however. – Jules – 2012-04-05T12:12:26.647

can simplify to: ageInput.hidden = ! this.checked; (I hate when people use boolean literals unnecessarily... if you are using both "true" and "false" in the same simple statement, it's probably unnecessary to use either) – JoelFan – 2015-03-06T20:38:14.567

44

I believe you could do this:

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

xenon

Posted 2009-05-23T15:16:39.917

Reputation: 1 330

alert($('input[name=isAgeSelected]').attr('checked'));

The above code shows true/false based on the check. Any problem with the previous tries – Prasad – 2009-05-23T15:41:43.157

Prasad, are you referencing your checkbox by name or ID? I'm getting confused now... – karim79 – 2009-05-23T15:52:26.603

i have referenced it by name – Prasad – 2009-05-23T16:08:54.107

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 – 2009-05-23T16:10:24.480

The .size() method is deprecated as of jQuery 1.8. Use the .length (with no () ;-) property instead ! And maybe you have to stick together "#isAgeSelected:checked". – François Breton – 2018-02-28T11:17:13.627

41

There are many ways to check if a checkbox is checked or not:

Way to check using jQuery

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

Check example or also document:

Parth Chavda

Posted 2009-05-23T15:16:39.917

Reputation: 1 524

40

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.

Nertim

Posted 2009-05-23T15:16:39.917

Reputation: 325

38

This works for me:

/* isAgeSelected being id for checkbox */

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

ashish amatya

Posted 2009-05-23T15:16:39.917

Reputation: 59

34

This is some different method to do the same thing:

$(document).ready(function (){

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

        // Using a pure CSS selector
        if ($(this.checked)) {
            alert('on check 1');
        };

        // Using jQuery's is() method
        if ($(this).is(':checked')) {
            alert('on checked 2');
        };

        //  // Using jQuery's filter() method
        if ($(this).filter(':checked')) {
            alert('on checked 3');
        };
    });
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

Sangeet Shah

Posted 2009-05-23T15:16:39.917

Reputation: 1 775

32

Use this:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

The length is greater than zero if the checkbox is checked.

Hamid N K

Posted 2009-05-23T15:16:39.917

Reputation: 29

31

You can use this code:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

sandeep kumar

Posted 2009-05-23T15:16:39.917

Reputation: 639

31

My way of doing this is:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}

Dalius I

Posted 2009-05-23T15:16:39.917

Reputation: 845

30

$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

Jumper Pot

Posted 2009-05-23T15:16:39.917

Reputation: 146

30

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

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

fe_lix_

Posted 2009-05-23T15:16:39.917

Reputation: 928

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';.

– WynandB – 2013-04-05T00:56:27.133

.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_ – 2013-04-25T10:02:28.123

As a side note, checking for undefined is better with typeof (x) !== "undefined" – naor – 2013-09-11T07:05:10.650

In that case, I believe it is more accurate and easier to read with !==. I would use the typeof(x) only when testing a variable that may or may not have been defined in the past. – fe_lix_ – 2013-09-18T08:04:23.307

28

You can use:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

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

Both of them should work.

Muhammad Awais

Posted 2009-05-23T15:16:39.917

Reputation: 1 805

24

This example is for button.

Try the following:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});

usayee

Posted 2009-05-23T15:16:39.917

Reputation: 43

23

The 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>

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.

MDMoore313

Posted 2009-05-23T15:16:39.917

Reputation: 1 799

23

1) If your HTML markup is:

<input type="checkbox"  />

attr used:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:

$(element).prop("checked") // Will return true whether checked="checked"

Somnath Kharat

Posted 2009-05-23T15:16:39.917

Reputation: 2 710

This is a REAL problem. My workaround - add a change event to the input: <input type="checkbox" onchange="ChangeChkBox()" /> then use that event to change a boolean JavaScript variable, and use the JavaScript variable instead of querying the checkbox directly. – Graham Laight – 2016-05-10T11:33:26.207

21

Toggle: 0/1 or else

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

user2385302

Posted 2009-05-23T15:16:39.917

Reputation: 24

19

I am using this:

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

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

Nishant Kumar

Posted 2009-05-23T15:16:39.917

Reputation: 2 809

19

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

Assuming that you have the following HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

You can use the following CSS to achieve the desired functionality:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

For other scenarios, you may think of appropriate CSS selectors.

Here is a Fiddle to demonstrate this approach.

Ormoz

Posted 2009-05-23T15:16:39.917

Reputation: 2 024

17

I think it will be the simple one

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

Jitendra Damor

Posted 2009-05-23T15:16:39.917

Reputation: 477

16

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

or

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

ijarlax

Posted 2009-05-23T15:16:39.917

Reputation: 415

15

I'm sure it's not some revelation, but I didn't see it all in one example:

Selector for all checked checkboxes(on the page):

$('input[type=checkbox]:checked')

Tsonev

Posted 2009-05-23T15:16:39.917

Reputation: 270

15

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

Joshua Harris

Posted 2009-05-23T15:16:39.917

Reputation: 360

14

Include jQuery from the local file system. I used Google's CDN, and there are also many CDNs to choose from.

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

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

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

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

        $(checkbox_selector).click(function() {
            if ($($(this)).is(':checked')) {

                // Disable all checkboxes
                $(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

Madan Sapkota

Posted 2009-05-23T15:16:39.917

Reputation: 16 173

13

Use:

<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.

UDB

Posted 2009-05-23T15:16:39.917

Reputation: 1 427

13

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

subham.saha1004

Posted 2009-05-23T15:16:39.917

Reputation: 484

12

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.

tsw_mik

Posted 2009-05-23T15:16:39.917

Reputation: 77

12

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)

Tim Abell

Posted 2009-05-23T15:16:39.917

Reputation: 6 101

11

Automated

$(document).ready(function()
{
    $('#isAgeSelected').change(function()
    {
        alert( 'value =' + $('#chkSelect').attr('checked') );
    });
});

HTML

<b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>

<br/><br/>

<input type="button" id="btnCheck" value="check" />

jQuery

$(document).ready(function()
{
    $('#btnCheck').click(function()
    {
        var isChecked = $('#isAgeSelected').attr('checked');

        if (isChecked == 'checked')
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    })
});

Ajax

function check()
{
    if (isAgeSelected())
        alert('check-box is checked');
    else
        alert('check-box is not checked');
}

function isAgeSelected()
{
    return ($get("isAgeSelected").checked == true);
}

Khaled.K

Posted 2009-05-23T15:16:39.917

Reputation: 5 052

10

This is the minimal amount of code I think I 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 this is how you use them:
checkedBoxes.each(function() {
    output +=  this.value + ", ";
};

Printing "output" will give you a comma-separated list of your values.

Daryl H

Posted 2009-05-23T15:16:39.917

Reputation: 504

9

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

cauleyfj

Posted 2009-05-23T15:16:39.917

Reputation: 21

9

Setter:

$("#chkmyElement")[0].checked = true;

Getter:

if($("#chkmyElement")[0].checked) {
   alert("enabled");
} else {
   alert("disabled");
}

JJ_Coder4Hire

Posted 2009-05-23T15:16:39.917

Reputation: 2 728

8

Use:

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

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

Richard Maxwell

Posted 2009-05-23T15:16:39.917

Reputation: 415

8

I would actually prefere the change event.

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

Demo Fiddle

Tarion

Posted 2009-05-23T15:16:39.917

Reputation: 6 945

8

Try this,

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

Mohammed Safeer

Posted 2009-05-23T15:16:39.917

Reputation: 9 698

6

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

user1996628

Posted 2009-05-23T15:16:39.917

Reputation: 21

6

A selector returns multiple objects, and it must take the first item in the array:

// Collection
var chckremember = $("#chckremember");


// Result boolen
var ischecked=chckremember[0].checked;

zamoldar

Posted 2009-05-23T15:16:39.917

Reputation: 361

6

I'm using jQuery 1.11.1 and I had troubles with setting and reading checkbox value as well.

I finally solved it by these two functions:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

It might looks a little bit dirty but it solves all the wired issue I had among different types of browsers.

Jacob

Posted 2009-05-23T15:16:39.917

Reputation: 1 482

6

Simply use it like below

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });

Himanshu Upadhyay

Posted 2009-05-23T15:16:39.917

Reputation: 418

3

What about this solution?

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

Iter Ator

Posted 2009-05-23T15:16:39.917

Reputation: 1 776

3

Using pure JavaScript:

let checkbox = document.getElementById('checkboxID');

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}

Carlos Abraham

Posted 2009-05-23T15:16:39.917

Reputation: 450

2

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

darhamid

Posted 2009-05-23T15:16:39.917

Reputation: 1 657

2

For older versions of jQuery, I had to use following,

$('#change_plan').live('click', function() {
     var checked = $('#change_plan').attr('checked');
     if(checked) {
          //Code       
     }
     else {
          //Code       
     }
});

Vajira Lasantha

Posted 2009-05-23T15:16:39.917

Reputation: 887

1

In case if you need to use CSS class as jQuery selector you can do following:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

It works fine for checkboxes and radioboxes as well.

Academy of Programmer

Posted 2009-05-23T15:16:39.917

Reputation: 17 258

1

This function is alternative and stable:

$('#isAgeSelected').context.checked
(return True/False)

Example:

if($('#isAgeSelected').context.checked){ //if Checkbox is checked then bla bla..
    /*.....*/
}else{
    /*.....*/
}

Ferhat KOÇER

Posted 2009-05-23T15:16:39.917

Reputation: 1 636

1

$('#chk').change(function() { 
    (this.checked)? alert('true') : alert('false');
});



($('#chk')[0].checked)? alert('true') : alert('false');

argie cruz

Posted 2009-05-23T15:16:39.917

Reputation: 123

0

$("#isAgeSelected").prop('checked', true);

Sudha

Posted 2009-05-23T15:16:39.917

Reputation: 149

2This code can set the checkbox to checked status.I do not think this answer is relative to the question. – bronze man – 2015-04-03T00:51:05.423

0

if($('#isAgeSelected').prop('checked')) {
    // do your action 
}

Vikash

Posted 2009-05-23T15:16:39.917

Reputation: 1 778

0

In case you need to know if a checkbox is checked in pure javascript you should use this code .

let checkbox =document.getElementById('myCheckboxId');
if(checkbox.checked) {
    alert("element is checked");
} else {
    alert("element is  ot checked");
}

Ir Calif

Posted 2009-05-23T15:16:39.917

Reputation: 144

0

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

E.X -

1) Run On load to get checkbox value if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box.

2) if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box using click event of checkbox.

so code not returns false by default:

Try the following:

<html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <h1>Jquery Demo</h1>
            <input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
            <div id="Age" style="display:none">
              <label>Enter your age</label>
              <input type="number" name="age">
            </div>
            <script type="text/javascript">
            if(document.getElementById('isAge').checked) {
                $('#Age').show();
            } else {
                $('#Age').hide();
            }   
            $('#isAge').click(function() {
                if(document.getElementById('isAge').checked) {
                    $('#Age').show();
                } else {
                    $('#Age').hide();
                }
            }); 
            </script>
        </body>
    </html>

Here is a modified version : https://jsfiddle.net/sedhal/0hygLtrz/7/

sedhal soni

Posted 2009-05-23T15:16:39.917

Reputation: 36

-12

For unchecking purposes this might help:

$('#chkbox').removeAttr('checked');

Anish Karunakaran

Posted 2009-05-23T15:16:39.917

Reputation: 648

1Why remove, wanted to check if the checkbox was checked. – tousif – 2015-06-13T21:20:59.280

1Just need to check the checked property of a checkbox. – Muhammad Awais – 2016-06-11T07:53:04.147

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone – 2016-07-29T05:47:55.637