By Prasad


2009-05-23 15:16:39 8 Comments

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

How do I successfully query the checked property?

30 comments

@Dan Walters 2019-10-03 09:50:54

To act on a checkbox being checked or unchecked on click.

<input type="checkbox" id="customCheck1">

 $('#customCheck1').click(function () {
        if (this.checked == true) {
            console.log('checked');
        }
        else {
            console.log('un-checked');
        }
    });

@Ajay Katariya 2019-10-03 08:20:13

You can try change event of checkbox

$("#isAgeSelected").on('change',function(){
    if($("#isAgeSelected").is(':checked'))
        alert("checked");  
    else{
         alert("unchecked");  
    }
});

@sandeep kumar 2016-10-13 06:03:19

This code will help you

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

@Kamil Kiełczewski 2019-08-28 04:39:14

In pure js checkbox state is easier to read

isAgeSelected.checked

function check() {
  txtAge.style.display= isAgeSelected.checked ? 'block':'none';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Age <input type="checkbox" id="isAgeSelected"/>

<button onclick="check()">Check</button>

<div id="txtAge" style="display:none">
Age is selected
</div>

@Javed Khan 2019-05-29 04:46:21

Please try below code to check checkbox is checked or not

$(document).ready(function(){

    $("#isAgeSelected").on('change',function(){

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

   });

});

@Praneeth Madush 2019-03-29 02:54:22

You Can Try This code:

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

@UDB 2013-09-29 15:45:05

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.

@Abraham Hernandez 2018-09-11 00:51:34

Using pure JavaScript:

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

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

@sedhal soni 2018-09-03 06:56:46

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/

@Ir Calif 2018-08-07 09:23:45

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

@Himanshu Upadhyay 2018-07-14 07:47:06

Simply use it like below

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

@Lalji Dhameliya 2016-08-29 11:38:19

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

@karim79 2009-05-23 15:20:33

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>

@Prasad 2009-05-23 15:24:20

i have tried the above condition too, but it returns false only

@karim79 2009-05-23 15:26:59

Something is amiss. In fact, the code you provided in your question should work. Are you referencing the correct element?

@Prasad 2009-05-23 15:35:16

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

@karim79 2009-05-23 15:39:34

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() {...

@Frans 2009-05-23 17:03:35

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.

@Mark Schultheiss 2010-03-26 20:17:13

@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

@Maksim Vi. 2010-10-04 20:55:23

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

@harry 2012-02-15 11:05:38

@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

@karim79 2012-03-06 10:14: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.

@duality_ 2013-09-26 14:05:08

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

@Gerson 2014-01-29 21:33:46

I prefer to use $("#txtAge").toggleClass("display-hide"); and <div id="txtAge" class="display-hide">Age is something</div>​ instead. But, it's the same idea. Anyway, your answer was helpful.

@JJ_Coder4Hire 2014-04-22 02:28:35

to set: $("#chkmyElement")[0].checked = true; to get: if($("#chkmyElement")[0].checked)

@user1106925 2015-05-17 03:06:51

@DCShannon: What do you think this.checked does?

@DCShannon 2015-05-18 18:37:34

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

@user1106925 2015-05-18 20:18:14

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

@pat capozzi 2015-05-20 16:30:58

according to jquery docs toggle is just to hide and show.

@Elendurwen 2015-08-03 20:42:45

This returns undefined

@Etienne Dupuis 2015-11-20 18:53:08

Note that if you want to animate the toggle, simply use the slideToggle animation: $("#txtAge").slideToggle(this.checked);

@cregox 2015-11-27 14:51:04

Why just @JJ_Coder4Hire brought up the [0] solution and almost nobody agreed? $('#isAgeSelected')[0].checked works perfectly!

@dwoodwardgb 2016-04-24 14:57:56

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.

@Erica Kane 2016-05-01 14:27:03

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

@Heretic Monkey 2017-05-22 15:45:17

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.

@Marc Compte 2017-07-06 10:58:14

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

@Jacob 2017-05-18 23:03:09

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.

@Hamid N K 2016-07-27 09:46:54

Use this:

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

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

@Sangeet Shah 2015-08-24 12:19:36

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>

@Ormoz 2015-08-22 19:09:46

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.

@zamoldar 2015-03-29 21:45:11

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;

@Parth Chavda 2014-10-14 07:48:07

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:

@ungalcrys 2014-05-20 20:03:29

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.

@vapcguy 2015-06-19 16:50:35

Technically, this.checked is using straight Javascript. But I love that cross-jQuery-version answer!

@Khaled.K 2014-05-14 05:42:19

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

@Tsonev 2013-11-15 10:50:44

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

@Somnath Kharat 2013-10-30 12:43:44

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"

@Graham Laight 2016-05-10 11:33:26

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.

@subham.saha1004 2013-10-10 06:23:22

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

@Nishant Kumar 2013-09-06 06:43: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();

@Daryl H 2013-07-15 15:50:34

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.

@Madan Sapkota 2013-03-02 05:38:24

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

@cauleyfj 2013-02-25 02:26:58

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

@Richard Maxwell 2013-01-23 16:40:06

Use:

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

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

@MDMoore313 2012-12-10 05:02:35

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.

Related Questions

Sponsored Content

86 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6032439 View
  • 7512 Score
  • 86 Answer
  • Tags:   javascript arrays

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

36 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

3 Answered Questions

40 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

21 Answered Questions

[SOLVED] Check if checkbox is checked with jQuery

34 Answered Questions

Sponsored Content