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
Patricia ArquetteOriginal
2024-11-13 04:32:02483browse

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;

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

jQuery (1.6 ):

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

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

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);

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!

Statement:
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