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!