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

ID : 60

viewed : 810

Tags : javascriptjqueryhtmlcheckboxjavascript





Top 5 Answer for javascript - How do I check whether a checkbox is checked in jQuery?

vote vote

98

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>

vote vote

84

Use jQuery's is() function:

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

76

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 } 
vote vote

62

jQuery 1.6+

$('#isAgeSelected').prop('checked') 

jQuery 1.5 and below

$('#isAgeSelected').attr('checked') 

Any version of jQuery

// Assuming an event handler on a checkbox if (this.checked) 

All credit goes to Xian.

vote vote

57

I am using this and this is working absolutely fine:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked"); 

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.

Top 3 video Explaining javascript - How do I check whether a checkbox is checked in jQuery?







Related QUESTION?