Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...