Search code examples
javascripthtmlformsradio-button

radio buttons won't check / uncheck


I have some radio buttons in my web page. when clicking the radio button it checks but when i click again it doesn't un-check. i tried to add a JS function onclick

document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
        if(this.checked == true){
            this.checked = false;
        }
        else {
            this.checked = true;
        }
    }))

when I added this method it allowed my to uncheck but didn't allow me to check any of them! what can I be missing?

these are my checkboxes:

<input type="radio" id="name" name="name"><br>
<input type="radio" id="age" name="age"><br>
<input type="radio" id="email" name="email"><br>

Solution

  • They all have different name attribute values - therefore they can only be checked (because they're not comparing to another sibling radio value). I think you might be looking for type="checkbox" instead:

    <input type="checkbox" id="name" name="name"><br>
    <input type="checkbox" id="age" name="age"><br>
    <input type="checkbox" id="email" name="email"><br>