Home  >  Article  >  Web Front-end  >  How to Dynamically Check or Uncheck Checkboxes with JavaScript?

How to Dynamically Check or Uncheck Checkboxes with JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 19:39:01932browse

How to Dynamically Check or Uncheck Checkboxes with JavaScript?

Manipulating Checkbox States Dynamically with JavaScript

JavaScript provides various methods to control the checked state of a checkbox from a web page. Here's how to check or uncheck a checkbox:

Using the Checked Property

The checked property of a element can be directly set to true or false to check or uncheck it.

<br>// Check<br>document.getElementById("checkbox").checked = true;</p>
<p>// Uncheck<br>document.getElementById("checkbox").checked = false;<br>

Using jQuery (v1.6 )

jQuery provides prop(), a more flexible method for manipulating element properties, including the checked state:

<br>// Check<br>$("#checkbox").prop("checked", true);</p>
<p>// Uncheck<br>$("#checkbox").prop("checked", false);<br>

Using jQuery (v1.5-)

Prior to jQuery v1.6, the attr() method was used for property manipulation. While still functional, it's not the most reliable approach for checkboxes:

<br>// Check<br>$("#checkbox").attr("checked", true);</p>
<p>// Uncheck<br>$("#checkbox").attr("checked", false);<br>

By leveraging these methods, you can dynamically update checkbox states, enabling you to build interactive web interfaces and control form inputs programmatically.

The above is the detailed content of How to Dynamically Check or Uncheck Checkboxes with JavaScript?. 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