Summary: In this tutorial, you will learn different ways to check whether a checkbox is checked or not using jQuery JavaScript library.
Approach 1:
To check if a checkbox is checked in jQuery, you can use the :checked
pseudo-selector in combination with the length
property:
if ($('#checkboxId').is(':checked')) {
// checkbox is checked
} else {
// checkbox is not checked
}
If the element with the ID checkboxId
is checked, the code inside the first block of the if
statement will be executed. Otherwise, the code inside the else
block will be executed.
Approach 2:
Use the prop
method to check the checked state of a checkbox. Here is an example:
if ($('#checkboxId').prop('checked')) {
// checkbox is checked
} else {
// checkbox is not checked
}
If the checked
property is set to true
, the code inside the first block of the if
statement will be executed. Otherwise, the code inside the else
block will be executed.
Approach 3:
Use the :checked
pseudo-selector to select all checked checkboxes and then use the length
property to determine how many checkboxes are checked.
var checked = $('input:checkbox:checked');
This will return a jQuery object containing all the checked checkboxes. Now you can check the length as follows:
if (checked.length > 0) {
// at least one checkbox is checked
} else {
// no checkboxes are checked
}
These were some of the ways using which you can easily check whether a checkbox is checked or not in Javascript code.