Home > Web Front-end > JS Tutorial > How to Toggle Checkbox State with JavaScript?

How to Toggle Checkbox State with JavaScript?

Susan Sarandon
Release: 2024-11-12 12:28:02
Original
1023 people have browsed it

How to Toggle Checkbox State with JavaScript?

How to Implement Checkbox Toggling Functionality with JavaScript

To manage the checked state of a checkbox dynamically, JavaScript offers efficient solutions. Let's explore the various approaches:

Toggling with Native JavaScript

Access the checkbox using its ID using document.getElementById("checkbox"). To check the box, set its checked property to true. Conversely, to uncheck it, set the property to false.

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

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

Toggling with jQuery (Version 1.6 )

With jQuery 1.6 and above, the prop method provides a convenient way to modify the checkbox state. To check the box, use $().prop("checked", true). To uncheck it, use $().prop("checked", false).

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

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

Toggling with jQuery (Versions 1.5 and below)

In earlier jQuery versions (1.5 and below), use the attr method to control the checkbox state. The syntax remains the same as in the prop method.

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

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

By utilizing these methods, you can seamlessly control the checked state of checkboxes based on user interactions or programmatic logic in your JavaScript code.

The above is the detailed content of How to Toggle Checkbox State with 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