Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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?

1 Answer

0 votes
by (40.7k points)

You will get the checked state of the element by using the checked property of the checkbox DOM element.

According to the code given by you, you can try using the code as follows:

if(document.getElementById('isAgeSelected').checked) {

    $("#txtAge").show();

} else {

    $("#txtAge").hide();

}

Another method is to use toggle like this:

$('#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>

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...