Home >Web Front-end >JS Tutorial >How to Dynamically Check or Uncheck Checkboxes 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:
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>
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>
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!