gpt4 book ai didi

javascript - 使用复选框启用/禁用表单输入元素组

转载 作者:搜寻专家 更新时间:2023-10-31 23:19:34 24 4
gpt4 key购买 nike

我想要一个可以启用(选中时)或禁用(未选中时)一组输入表单元素的复选框。我已经设法只用一个元素来做到这一点,但我正在努力用几个元素来做到这一点。这是我的代码:

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/

最佳答案

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;
}
}
}
<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">

这是相同的工作 fiddle :https://jsfiddle.net/prerak6962/g96j4g7g/2/

关于javascript - 使用复选框启用/禁用表单输入元素组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com