Sign Up

Sign In

Forget Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

How to check whether a checkbox is checked in jQuery?

  • 0

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?

Click to rate this post!
[Total: 0 Average: 0]
Share This Post
Share
  1. The checked property of a checkbox DOM element will 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);
    });
    <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>
    • 0
Leave an answer

Leave an answer

Browse

close