How to make checkbox behave like radio buttons with JavaScript?

Sometimes, we want to make checkbox behave like radio buttons with JavaScript.

In this article, we’ll look at how to make checkbox behave like radio buttons with JavaScript.

How to make checkbox behave like radio buttons with JavaScript?

To make checkbox behave like radio buttons with JavaScript, we can listen to the body element’s click listener.

And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that’s clicked.

For instance, we write:

<label>
  <input type="checkbox" name="cb1" class="chb" />
  CheckBox1
</label>
<label>
  <input type="checkbox" name="cb2" class="chb" />
  CheckBox2
</label>
<label>
  <input type="checkbox" name="cb3" class="chb" />
  CheckBox3
</label>
<label>
  <input type="checkbox" name="cb4" class="chb" />
  CheckBox4
</label>

to add the checkboxes.

Then we write:

const checkboxes = document.querySelectorAll('.chb')

document.body.addEventListener('click', (e) => {
  for (const c of checkboxes) {
    c.checked = false
  }

  const clickedCheckbox = [...checkboxes].find(c => c === e.target)
  clickedCheckbox.checked = true
})

We select the checkboxes with document.querySelectorAll.

Then we add a click listener to the body element with document.body.addEventListener.

In the click listener, we loop through the checkboxes with the for-of loop and set the checked property of all of them to false.

Then we find the checkbox that matches the one we clicked by spreading the checkboxes into an array and then use the find method and check which one matches the e.target.

e.target has the item that’s clicked.

Then finally, we set the checked property of the checkbox that matches to true.

Conclusion

To make checkbox behave like radio buttons with JavaScript, we can listen to the body element’s click listener.

And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that’s clicked.