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?
This is some different method to do the same thing:
1) If your HTML markup is:
attr used:
If prop is used:
2) If your HTML markup is:
attr used:
Prop used:
This worked for me:
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
You can use this code:
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 usejQuery.prop()
:Two other possibilities are:
The top answer didn't do it for me. This did though:
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.