Two ways to obtain the selected state of a checkbox
There are two ways to get the checked status of a checkbox:
- Retrieve a reference to the checkbox element using the document.getElementById() method.
- We can use the checkbox.checked property to determine if the checkbox is checked. If the checkbox is checked, the value of this property will be true; otherwise, it will be false.
var checkbox = document.getElementById('myCheckbox');
if (checkbox.checked) {
// checkbox被选中
} else {
// checkbox未被选中
}
- Select the checkbox element using a selector.
- Use the prop() method in jQuery to get the checked status of a checkbox. If the checkbox is checked, the method will return true; otherwise it will return false.
if ($('#myCheckbox').prop('checked')) {
// checkbox被选中
} else {
// checkbox未被选中
}
Regardless of the method used, you first need to obtain a reference to the checkbox element, and then use the checked property or the prop() method to get its checked status.