javascript - How to check whether a checkbox is checked in jQuery?


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?


Answers



How do I successfully query the checked property?

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>




Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked



Using jQuery > 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

Using the new property method:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}



Checkbox value is always 'on'

Use .is(':checked') instead: Working jsFiddle

var eu_want_team = $('#eu_want_team').is(':checked');
alert(eu_want_team);

or as @Itay said in comments you can use jQuery's .prop() to get the checked property value:

alert($("#eu_want_team").prop("checked"));



<label class="checkbox">
    <input id="eu_want_team" name="eu_want_team" type="checkbox" value="somevalue">
</label>

<script>
   var ele = document.getElementById("eu_want_team");
   if(ele.checked)
   alert(ele.value)

</script>






Determine if Checkbox is Checked using jQuery

You would use the checked selector along with the is method of Jquery

if($('#chkbox').is(':checked')){

}



You can see if the checkbox is checked by using the following condition.

   if( $("input:checked").length == 1 ) {
           //Checkbox is selected and Do stuff here
       }



get current state of check box jquery

Try to use .is() function along with :checked selector to accomplish your task,

ckb = $("#ickb").is(':checked');



Use is() with :checked to get the result as boolean that is true if checkbox is checked.

ckb = $("#ickb").is(':checked');

Or, you can use length, if it is zero then it is not checked.

ckb = $("#ickb::checked").length