4 checkboxes if one checked other unchecked in javascript

You can achieve this functionality by adding event listeners to all the checkboxes and then tracking changes to their checked property. Whenever a checkbox is checked, you can uncheck all the other checkboxes. Here's an example code:

<input type="checkbox" id="check1">
<input type="checkbox" id="check2">
<input type="checkbox" id="check3">
<input type="checkbox" id="check4">
144 chars
5 lines
index.tsx
const checkboxes = document.querySelectorAll('input[type="checkbox"]');

checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    if (this.checked) {
      checkboxes.forEach(function(c) {
        if (c !== checkbox) {
          c.checked = false;
        }
      });
    }
  });
});
322 chars
14 lines

The above code uses querySelectorAll to select all the checkboxes on the page, and then adds an event listener to each checkbox that triggers whenever the change event is fired. When a checkbox is checked, the code sets all other checkboxes to unchecked by setting their checked property to false.

gistlibby LogSnag