4 checkboxes if one of them is checked all other should be unchecked in javascript

To achieve this functionality, we can add event listeners to each of the checkboxes and then uncheck the other checkboxes in the event listener of the checkbox that is checked. Here's an example code:

<input type="checkbox" id="cb1">
<input type="checkbox" id="cb2">
<input type="checkbox" id="cb3">
<input type="checkbox" id="cb4">

<script>
  const checkboxes = document.querySelectorAll('input[type=checkbox]');

  checkboxes.forEach(checkbox => {
    checkbox.addEventListener('change', function() {
      if (this.checked) {
        checkboxes.forEach(chk => {
          if (chk !== this) {
            chk.checked = false;
          }
        });
      }
    });
  });
</script>
484 chars
21 lines

In this code, we first select all the checkboxes using document.querySelectorAll('input[type=checkbox]'). Then, we add a change event listener to each checkbox using the forEach method. In this event listener, we check if the checkbox that triggered the event is checked or not. If it's checked, we loop over all the other checkboxes and uncheck them if they are not the same as the checkbox that triggered the event. This way, only one checkbox can be checked at a time.

gistlibby LogSnag