How to select only one checkbox in a group with HTML and JavaScript?

Spread the love

Sometimes, we want to select only one checkbox in a group with HTML and JavaScript.

In this article, we’ll look at how to select only one checkbox in a group with HTML and JavaScript.

How to select only one checkbox in a group with HTML and JavaScript?

To select only one checkbox in a group with HTML and JavaScript, we uncheck the checkboxes other than the checked ones.

For instance, we write

<div class="test-checkbox">
  Group One:
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupOne"
      value="Eat"
    />Eat
  </label>
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupOne"
      value="Sleep"
    />Sleep
  </label>
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupOne"
      value="Play"
    />Play
  </label>
  <br />
  Group Two:
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupTwo"
      value="Fat"
    />Fat
  </label>
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupTwo"
      value="Comfort"
    />Comfort
  </label>
  <label>
    <input
      type="checkbox"
      data-limit="only-one-in-a-group"
      name="groupTwo"
      value="Happy"
    />Happy
  </label>
</div>

to add the checkboxes.

Then we write

const uncheckOthers = (clicked) => {
  const name = clicked.getAttribute("name");
  [...cbxes].forEach((other) => {
    if (other !== clicked && other.getAttribute("name") === name) {
      other.checked = false;
    }
  });
};

const cbxes = document.querySelectorAll(
  'input[type="checkbox"][data-limit="only-one-in-a-group"]'
);
[...cbxes].forEach((cbx) => {
  cbx.addEventListener("change", (e) => {
    if (e.target.checked) {
      uncheckOthers(e.target);
    }
  });
});

to define the uncheckOthers function to uncheck all the checkboxes that aren’t checked.

We check if the checkbox should be unchecked with

other !== clicked && other.getAttribute("name") === name

Then we select all checkboxes with querySelectorAll.

We call forEach with a callback that adds a change listener to each checkbox with addEventListener.

If the element is checked according to e.target.checked, then we call uncheckOthers to uncheck the checkboxes other than the e.target checkbox.

e.target is the checkbox that triggered then change event.

Conclusion

To select only one checkbox in a group with HTML and JavaScript, we uncheck the checkboxes other than the checked ones.

Leave a Reply

Your email address will not be published. Required fields are marked *