as we know, html radio button is a single choice, so we can't select more than one radio button.
radio buttonโ
Live Editor
Result
Loading...
radio button are usually used in scenarios where the user selects an item from a set of options. Once the user selects an item, it cannot be clicked again to cancel the selection.
unchecked radio buttonโ
The radio buttons provided by default cannot be unselected, so they have to be handled by the click
event.
<form>
<label> <input type="radio" name="like" /> Item A </label>
<label> <input type="radio" name="like" /> Item B </label>
</form>
we can set the checked
attribute to false
to uncheck the radio button.
const radioEls = document.querySelectorAll("input[type=radio]");
radioEls.forEach((el) => {
el._checked = el.checked;
el.addEventListener("click", (e) => {
const target = e.target;
if (target._checked) {
target.checked = target._checked = false;
} else {
document.querySelectorAll(`input[name=${target.name}]`).forEach((el) => {
el.checked = el._checked = false;
});
target.checked = target._checked = true;
}
});
});