JavaScript Checkbox: checked, Groups and Validation

Checkbox controls in JavaScript

A checkbox represents an independent on/off choice. JavaScript reads its selection through the Boolean checked property, its submitted data through name and value, and its availability through disabled.

<label><input type="checkbox" id="news" name="news" value="yes"> Email updates</label>
const news = document.getElementById("news");
console.log(news.checked);

Use checkboxes when a user may choose zero, one, or several options. Use radio buttons when a group should permit only one choice. See also the older radio/period-button example.

Table of Contents

Read and Change Checkbox State Top ↑

checked is true when the box is selected and false otherwise. Assigning a Boolean changes the state.

const agree = document.getElementById("agree");
if (agree.checked) {
  console.log("Selected");
}
agree.checked = true;

Work with a Group of Checkboxes Top ↑

Give related checkboxes the same name. JavaScript can then collect the group and read only the selected values. The checkbox array tutorial develops this pattern.

const selected = [...document.querySelectorAll('input[name="skills"]:checked')]
  .map((box) => box.value);
console.log(selected);

Respond to Checkbox Changes Top ↑

Prefer addEventListener() over inline onclick attributes for new code.

const option = document.getElementById("option1");
option.addEventListener("change", () => {
  console.log(option.checked);
});

Validate Checkbox Selections Top ↑

HTML can handle a simple required confirmation with required. JavaScript is useful for group rules such as “choose at least two” or “choose no more than three.” See checkbox validation and selection limits.

<label><input type="checkbox" name="terms" required> I agree</label>

Enable or Disable a Checkbox Top ↑

const option = document.getElementById("option1");
option.disabled = true;
option.disabled = false;

See enable or disable a checkbox. The related enable/disable form-control tutorial uses a checkbox to control another input.




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer