To check if a checkbox is checked using jQuery, you can use the prop()
method to get the value of the "checked" property of the checkbox element.
Here's an example code snippet:
javascriptif ($('#myCheckbox').prop('checked')) {
// Checkbox is checked
} else {
// Checkbox is not checked
}
In this code, $('#myCheckbox')
selects the checkbox element using its ID, and prop('checked')
gets the value of the "checked" property. If the checkbox is checked, the prop()
method will return true
, and the code inside the if
block will execute. If the checkbox is not checked, the prop()
method will return false
, and the code inside the else
block will execute.
Alternatively, you can also use the is()
method to check if the checkbox is checked, like this:
javascriptif ($('#myCheckbox').is(':checked')) {
// Checkbox is checked
} else {
// Checkbox is not checked
}
This code is equivalent to the first example, but uses the is()
method to check if the checkbox is checked. The :checked
selector matches all checked checkboxes, so $('#myCheckbox').is(':checked')
returns true
if the checkbox is checked.
jQuery, jQuery Interview Question and Answers, jQuery Tutorial
Comments
Post a Comment