单选按钮不会选中/取消选中

radio buttons won't check / uncheck

我的网页中有一些单选按钮。 单击单选按钮时它会选中,但当我再次单击时它不会取消选中。 我尝试添加一个 JS 函数 onclick

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

当我添加此方法时,它允许我取消选中但不允许我选中其中任何一个! 我可以缺少什么?

这些是我的复选框:

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

示例:按住Ctrl(mac上的)键取消选中。

var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
    radios[i].onclick = function(e) {
        if(e.ctrlKey || e.metaKey) {
            this.checked = false;
        }
    }
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />

使用 <input type="checkbox",而不是 <input type="radio"。 单选按钮用于您必须 select 某些选项之一(必须具有相同的 name)。

例如,

<input type="radio" name="gender" id="male" value="male"> <br>
<input type="radio" name="gender" id="female" value="female"> <br>
<input type="radio" name="gender" id="other" value="other">

进一步了解 radio button and check boxes

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

          this.checked = false;
          document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
          this.value = 0;
      }      
}))
<input type="radio" value="0" id="name" name="test"><br>
<input type="radio" value="0" id="age" name="test"><br>
<input type="radio" value="0" id="email" name="test"><br>

它们都有不同的 name 属性值 - 因此它们 只能 被检查(因为它们不与另一个同级无线电值进行比较)。我认为您可能正在寻找 type="checkbox" 而不是:

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