Home > Web Front-end > JS Tutorial > How to Control the Checked State of a Checkbox using JavaScript?

How to Control the Checked State of a Checkbox using JavaScript?

Patricia Arquette
Release: 2024-11-13 04:32:02
Original
466 people have browsed it

How to Control the Checked State of a Checkbox using JavaScript?

JavaScript Checkbox Control

Controlling the checked state of a checkbox using JavaScript is a versatile technique for web development. To accomplish this, there are several approaches:

Pure JavaScript:

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

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

This method directly accesses the checked property of the checkbox element.

jQuery (1.6 ):

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

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

jQuery's prop() method allows the manipulation of checkbox properties, including the checked state.

jQuery (1.5-):

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

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

The older attr() method is provided for backward compatibility but is recommended to use prop() instead. Both methods directly alter the checked attribute.

Utilizing these techniques to manipulate checkbox states enables greater control over user interactions and form functionality in JavaScript-based web applications.

The above is the detailed content of How to Control the Checked State of a Checkbox 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