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?
Use this:
The length is greater than zero if the checkbox is checked.
I ran in to the exact same issue. I have an ASP.NET checkbox
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.
I'm sure you can also use the ID instead of the CssClass,
I hope this helps you.
I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.
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 thehidden
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.Slower but cross-browser compatible.
Using the
Click
event handler for the checkbox property is unreliable, as thechecked
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).Using jQuery > 1.6
Using the new property method:
I believe you could do this: