Home > Article > Web Front-end > 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;
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);
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);
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!