How to check whether a checkbox is checked or not using jQuery
In this post, we will discuss How to check whether a checkbox is checked or not using jQuery. The following section describes how to check the status of checkboxes whether it is checked or not using the jQuery prop() method as well as: the checked selector.
Using prop() Method
The jQuery prop() method is used to provide a simple, effective, and reliable way to track down the current status of a checkbox.
Note: The checked attribute only defines the initial state of a checkbox and not the current state.
Also read: How to get checkbox selected value in jquery
Example
<!DOCTYPE html>
<html>
<head>
<title>How to check a checkbox is checked or not using jQuery - devnote.in </title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Using prop() Method</h1>
<input type="checkbox" name="hobbies" class="hobbies" id="hobbies">
<label for="hobbies">Select hobbies</label>
</body>
<script>
$(document).ready(function(){
$('.hobbies').click(function(){
if($(this).prop("checked") == true) {
console.log("Checkbox is checked.");
} else if($(this).prop("checked") == false) {
console.log("Checkbox is unchecked.");
}
});
});
</script>
</html>
Using : checked Selector
The jQuery:checked selector is used to check the status of checkboxes. The:checked selector is specifically designed for checkboxes and radio buttons.
Example
<!DOCTYPE html>
<html>
<head>
<title>How to check a checkbox is checked or not using jQuery - devnote.in </title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Using :checked Selector</h1>
<input type="checkbox" name="hobbies" class="hobbies" id="hobbies">
<label for="hobbies">Select hobbies</label>
</body>
<script>
$(document).ready(function() {
$('.hobbies').click(function() {
if($(this).is(":checked")) {
console.log("Checkbox is checked.");
} else if($(this).is(":not(:checked)")) {
console.log("Checkbox is unchecked.");
}
});
});
</script>
</html>