Home >Web Front-end >JS Tutorial >How to Properly Check or Uncheck a Checkbox Using jQuery?
Many developers would like to set the "checked" attribute of a checkbox using jQuery, and some might try to use methods like .checked() or .selected(). However, these methods do not exist in jQuery.
To set the "checked" attribute in modern versions of jQuery, use the .prop() method:
$('.myCheckBox').prop('checked', true); // Check the checkbox $('.myCheckBox').prop('checked', false); // Uncheck the checkbox
Another option is to access the underlying HTMLInputElement object and directly set the .checked property:
$('.myCheckBox')[0].checked = true; // Check the checkbox $('.myCheckBox')[0].checked = false; // Uncheck the checkbox
For older versions of jQuery (prior to 1.6), the .prop() method is not available, so you can use .attr() instead:
$('.myCheckBox').attr('checked', true); // Check the checkbox $('.myCheckBox').attr('checked', false); // Uncheck the checkbox
It's important to note that while using .removeAttr('checked') may seem like a reasonable approach, it can lead to unexpected behavior when interacting with forms that include the checkbox. Therefore, using .prop() or .attr() is the preferred method for setting the "checked" attribute with jQuery.
The above is the detailed content of How to Properly Check or Uncheck a Checkbox Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!