Home >Web Front-end >JS Tutorial >How Do I Programmatically Check or Uncheck a Checkbox with jQuery?
When working with checkboxes using jQuery, you may encounter a need to set the "checked" state programmatically. While methods like ".checked(true)" or ".selected(true)" do not exist in jQuery, there are several alternative ways to achieve this functionality:
Utilize the .prop() method:
$('.myCheckbox').prop('checked', true); $('.myCheckbox').prop('checked', false);
For manipulating a single element, access the underlying HTMLInputElement and directly set the ".checked" property:
$('.myCheckbox')[0].checked = true; $('.myCheckbox')[0].checked = false;
In earlier jQuery versions, the .prop() method is unavailable. Use .attr() instead:
$('.myCheckbox').attr('checked', true); $('.myCheckbox').attr('checked', false);
Note that using .attr() is preferable to .removeAttr('checked') as it preserves the box's initial checked state and prevents unintended behavior upon form resets.
The above is the detailed content of How Do I Programmatically Check or Uncheck a Checkbox with jQuery?. For more information, please follow other related articles on the PHP Chinese website!