Home >Web Front-end >JS Tutorial >How Do I Programmatically Check or Uncheck a Checkbox with jQuery?

How Do I Programmatically Check or Uncheck a Checkbox with jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 02:19:09870browse

How Do I Programmatically Check or Uncheck a Checkbox with jQuery?

Setting "checked" for 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:

Modern jQuery

Utilize the .prop() method:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

For manipulating a single element, access the underlying HTMLInputElement and directly set the ".checked" property:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

jQuery 1.5.x and Below

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn