4 checkboxes if one of them get checked then all others get unchecked in javascript

Here's an example code snippet that demonstrates how to implement this behavior using JavaScript:

<!-- HTML -->
<input type="checkbox" id="checkbox1" onclick="onCheckboxClick('checkbox1')">
<input type="checkbox" id="checkbox2" onclick="onCheckboxClick('checkbox2')">
<input type="checkbox" id="checkbox3" onclick="onCheckboxClick('checkbox3')">
<input type="checkbox" id="checkbox4" onclick="onCheckboxClick('checkbox4')">
326 chars
6 lines
index.tsx
// JavaScript
function onCheckboxClick(id) {
  const checkboxes = document.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach(checkbox => {
    if (checkbox.id !== id) {
      checkbox.checked = false;
    }
  });
}
230 chars
10 lines

In this example, we're using the querySelectorAll method to select all four checkboxes on the page. We're then looping through each checkbox and checking if its ID matches the one that was clicked. If it doesn't match, we uncheck it. This ensures that only the checkbox that was clicked is checked, and all the others are unchecked.

Finally, we're calling this onCheckboxClick function whenever any of the checkboxes are clicked, passing in the ID of the clicked checkbox as an argument.

gistlibby LogSnag