Organizational Research By

Surprising Reserch Topic

Check checkbox checked property


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?

 


asked Jun 30, 2015 in JAVASCRIPT by rajesh
0 votes
81 views



Related Hot Questions

2 Answers

0 votes

The .checked property of a checkbox DOM element will tell 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);
});

<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is somethingdiv>‚Äč
answered Jun 30, 2015 by rajesh
0 votes

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

answered Jun 30, 2015 by rajesh

...