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

How Do I Check or Uncheck a Checkbox Using jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 11:46:09246browse

How Do I Check or Uncheck a Checkbox Using jQuery?

Setting "checked" for a checkbox with jQuery

To select a checkbox using jQuery, we can use the .prop() method to modify the underlying HTMLInputElement's .checked property.

Modern jQuery

Use .prop():

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

DOM API

If working with a single element:

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

jQuery 1.5.x and below

Before jQuery version 1.6, use .attr() instead of .prop():

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

Note that this approach is preferred over using .removeAttr('checked'), as it prevents unintended behavior changes when calling .reset() on forms containing the checkbox.

The above is the detailed content of How Do I Check or Uncheck a Checkbox Using 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