如何使用顺序ID禁用多个单选按钮?

时间:2016-04-27 18:54:07

标签: javascript html

我需要禁用所有单选按钮;最好的方法是使用javascript,但我不太擅长;我尝试循环id,但这是一场灾难! 我最终使用6行来禁用每个单选按钮;我可以更有效地做到这一点

document.getElementById("radio1").disabled = true;
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
document.getElementById("radio4").disabled = true;
document.getElementById("radio5").disabled = true;
document.getElementById("radio6").disabled = true;
Radio Buttons:<br>
<input type="radio" id="radio1">1<br>
<input type="radio" id="radio2">2<br>
<input type="radio" id="radio3">3<br>
<input type="radio" id="radio4" checked>4<br>
<input type="radio" id="radio5">5<br>
<input type="radio" id="radio6">6

4 个答案:

答案 0 :(得分:2)

您可以使用querySelectorAll()选择type="radio"的所有输入,然后使用循环在每个输入上设置disabled = true

var inputs = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < inputs.length; i++) {
  inputs[i].disabled = 'true';
}
Radio Buttons:
<br>
<input type="radio" id="radio1">1<br>
<input type="radio" id="radio2">2<br>
<input type="radio" id="radio3">3<br>
<input type="radio" id="radio4" checked>4<br>
<input type="radio" id="radio5">5<br>
<input type="radio" id="radio6">6

答案 1 :(得分:2)

不确定为什么循环是一场灾难。我就是这样做的:

for (var i = 1; i <= 6; i++) {
    document.getElementById("radio" + i).disabled = true;
}

可替换地:

var ids = ['radio1', 'radio2', 'radio3', 'radio4', 'radio5', 'radio6'];

ids.forEach(function (id) {
    document.getElementById(id).disabled = true;
});

答案 2 :(得分:1)

您可以使用css选择器(document.querySelectorAll):

var radios = document.querySelectorAll("[id^='radio']"); //get all elements that have an id starting with 'radio'
for (var i = 0; i < radios.length; i++) {
    radios[i].disabled = true;
}

答案 3 :(得分:0)

你可以沿着这些方向做点什么

// load all the inputs in the document into memory
var inputs = document.getElementsByTagName("input");

// loop over them, and set the disabled attribute on each of them
for (var i = 0; i < inputs.length; i++) {    
    inputs[i].disabled = true; 
}

请注意,通过执行document.getElementsByTagName("input"),您可以在页面中收集所有输入,因此更好的方法是将它们包装在容器中,并在其上执行表达式,如这样:

<div id="input-container">
   <input type="radio" id="radio1">
   ...
</div>

然后

var container = document.getElementById("input-container");
var inputs = container.getElementsByTagName("input");

循环保持不变