4 checkboxes that act like radiobuttons in javascript

To create 4 checkboxes that act like radio buttons in JavaScript, you can use the following code:

  1. HTML code including checkbox inputs
<input type="checkbox" id="option1" name="option" onclick="handleClick(this)">
<label for="option1">Option 1</label>

<input type="checkbox" id="option2" name="option" onclick="handleClick(this)">
<label for="option2">Option 2</label>

<input type="checkbox" id="option3" name="option" onclick="handleClick(this)">
<label for="option3">Option 3</label>

<input type="checkbox" id="option4" name="option" onclick="handleClick(this)">
<label for="option4">Option 4</label>
471 chars
12 lines
  1. JavaScript code to act like radio buttons
index.tsx
let prevChecked = null;

// function to handle click on checkboxes
function handleClick(currCheckbox) {
  // uncheck all checkboxes except the one clicked
  if (prevChecked !== null && prevChecked !== currCheckbox) {
    prevChecked.checked = false;
  }
  prevChecked = currCheckbox;
}
286 chars
11 lines

In this code, we keep track of the previously checked checkbox using the prevChecked variable. When a checkbox is clicked, we uncheck all checkboxes except the current checkbox. Finally, we update the prevChecked variable with the current checkbox.

Note: It is important to have name="option" for all checkboxes to ensure they behave like radio buttons.

gistlibby LogSnag