To check whether a checkbox is checked in jQuery, you can use the is
function and pass it the :checked
selector. The :checked
selector matches elements that are checked, such as checkboxes and radio buttons.
Here is an example of how to use the :checked
selector to check if a checkbox is checked:
if ($('#my-checkbox').is(':checked')) {
console.log('Checkbox is checked');
} else {
console.log('Checkbox is not checked');
}
You can also use the prop
function to get the checked
property of the checkbox element. The checked
property is a boolean value that indicates whether the checkbox is checked or not.
if ($('#my-checkbox').prop('checked')) {
console.log('Checkbox is checked');
} else {
console.log('Checkbox is not checked');
}
Note that the :checked
selector and the checked
property will only work for checkboxes that are checked manually by the user. If you want to check whether a checkbox is checked programmatically, you can use the attr
function to get the checked
attribute of the checkbox element.
if ($('#my-checkbox').attr('checked') !== undefined) {
console.log('Checkbox is checked');
} else {
console.log('Checkbox is not checked');
}