Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Toggle between set of checkboxes and uncheck the checked one when clicked

i have three checkboxes on my page and i want just one to be selected. If user clicks on another checkbox i uncheck the current one and check the clicked one. The problem here is that when a user check a box he just can’t uncheck it… he can move to another one but i want to give the user option to uncheck the checked one as well. Any ideas? Thanks.

    const checkBoxes = document.querySelectorAll('input[type="checkbox"]');
    checkBoxes.forEach((checkBox) => {
        checkBox.addEventListener('click', () => {
            checkBoxes.forEach((checkBox) => {
                checkBox.checked = false;
            });

            checkBox.checked = true;

        });

    });
        <input type="checkbox" value="Option1">
        <input type="checkbox" value="Option2">
        <input type="checkbox" value="Option3">

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Loop over all the checkboxes and only uncheck the ones that are not the clicked checkbox. Let the checkbox that you clicked handle itself.

const checkBoxes = document.querySelectorAll('input[type="checkbox"]');

function handleCheckboxClick(event) {
  checkBoxes.forEach((checkBox) => {
    if (event.target !== checkBox) {
      checkBox.checked = false;
    }
  });
}

checkBoxes.forEach((checkBox) => {
  checkBox.addEventListener('click', handleCheckboxClick);
});
<input type="checkbox" value="Option1">
<input type="checkbox" value="Option2">
<input type="checkbox" value="Option3">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading