Home > Web Front-end > JS Tutorial > How can I programmatically check or uncheck checkboxes using JavaScript?

How can I programmatically check or uncheck checkboxes using JavaScript?

Susan Sarandon
Release: 2024-11-24 18:43:39
Original
575 people have browsed it

How can I programmatically check or uncheck checkboxes using JavaScript?

Manipulating Checkboxes with JavaScript

Often faced with the need to dynamically manage input elements, developers might wonder about controlling checkboxes in JavaScript. This question explores methods for checking and unchecking checkboxes using JavaScript.

JavaScript

To check or uncheck a checkbox using JavaScript, access the element using its ID and modify its checked property:

// Check checkbox
document.getElementById("checkbox").checked = true;

// Uncheck checkbox
document.getElementById("checkbox").checked = false;
Copy after login

jQuery (1.6 )

In jQuery versions 1.6 and above, utilize the prop() method to manipulate the checkbox state:

// Check checkbox
$("#checkbox").prop("checked", true);

// Uncheck checkbox
$("#checkbox").prop("checked", false);
Copy after login

jQuery (1.5-)

For jQuery versions 1.5 and below, use the attr() method to control the checkbox:

// Check checkbox
$("#checkbox").attr("checked", true);

// Uncheck checkbox
$("#checkbox").attr("checked", false);
Copy after login

By employing these techniques, developers can dynamically manage checkbox states in web applications, allowing for improved user interactions and streamlined user interfaces.

The above is the detailed content of How can I programmatically check or uncheck checkboxes using JavaScript?. 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