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
Release: 2024-12-21 02:19:09
Original
863 people have browsed it

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);
Copy after login

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;
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template