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 jQuery's is() function:
You can use:
Both of them should work.
There are many ways to check if a checkbox is checked or not:
Way to check using jQuery
Check example or also document:
http://api.jquery.com/attr/
http://api.jquery.com/prop/
Though you have proposed a JavaScript solution for your problem (displaying a
textbox
when acheckbox
ischecked
), 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:
You can use the following CSS to achieve the desired functionality:
For other scenarios, you may think of appropriate CSS selectors.
Here is a Fiddle to demonstrate this approach.
Toggle: 0/1 or else
I think it will be the simple one