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">
Advertisement
Answer
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">