我想要一个可以启用(选中时)或禁用(取消选中时)一组输入表单元素的复选框。我已经设法只使用一个单独的元素,但我正在努力用几个元素来做。这是我的代码:
使用Javascript:
function myFunction() {
var elements = document.getElementsByClassName("child1");
var el = document.getElementById("myCheck");
for(var i=0; i<elements.length; i++) {
if(el.checked) {
elements[i].removeAttribute("disabled");
} else {
elements[i].setAttribute("disabled","disabled");
}
}
}
HTML
<input type="checkbox" id="myCheck" onChange="myFunction()">Click the button to disable the form input elements<br>
<input type="radio" class="child1" name="group1" disabled="disabled">
<input type="radio" class="child1" name="group1" disabled="disabled">
<input type="radio" class="child1" name="group1" disabled="disabled">
<br>
<input type="radio" class="child1" name="group2" disabled="disabled">
<input type="radio" class="child1" name="group2" disabled="disabled">
<input type="radio" class="child1" name="group2" disabled="disabled">
<br>
<input type="text" class="child1" disabled="disabled">
(我已经使用了getElementsByClassName,因为我知道你只能通过html页面拥有一个ID(即getElementById不起作用))。
JSFIDDLE https://jsfiddle.net/w2992L1y/
答案 0 :(得分:4)
disabled属性没有与之关联的值。因此,要禁用输入元素,您只需执行<input disabled>
。与使用JavaScript启用/禁用输入元素类似,您需要执行以下操作:
element.disabled = true; //disable
element.disabled = false; //enable
对于您的示例,您可以执行以下操作:
function myFunction() {
var elements = document.getElementsByClassName("child1");
var el = document.getElementById("myCheck");
for (var i = 0; i < elements.length; i++) {
if (el.checked) {
elements[i].disabled = true;
} else {
elements[i].disabled = false;
}
}
}
&#13;
<input type="checkbox" id="myCheck" onChange="myFunction()">Click the button to disable the form input elements
<br>
<input type="radio" class="child1" name="group1">
<input type="radio" class="child1" name="group1">
<input type="radio" class="child1" name="group1">
<br>
<input type="radio" class="child1" name="group2">
<input type="radio" class="child1" name="group2">
<input type="radio" class="child1" name="group2">
<br>
<input type="text" class="child1">
&#13;
这是同样的工作小提琴:https://jsfiddle.net/prerak6962/g96j4g7g/2/