Home > Web Front-end > JS Tutorial > How to Properly Check or Uncheck a Checkbox Using jQuery?

How to Properly Check or Uncheck a Checkbox Using jQuery?

DDD
Release: 2024-12-19 09:38:11
Original
255 people have browsed it

How to Properly Check or Uncheck a Checkbox Using jQuery?

Setting "checked" for a Checkbox with 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.

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

DOM API

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

jQuery 1.5.x and Below

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template