使用 javascript 启用和禁用复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16163507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:31:25  来源:igfitidea点击:

Enabling and disabling checkboxes with javascript

javascriptforms

提问by Sadfsa Asffds

I have been trying to figure out the solution to my problem for a few hours now. I'm still fairly new to Javascript, so please forgive me if I sound stupid. Sadly I don't know jQuery and I'm starting to think that it's inhibiting me to come up with a solution.

几个小时以来,我一直试图找出我的问题的解决方案。我对 Javascript 还是很陌生,所以如果我听起来很愚蠢,请原谅我。遗憾的是我不知道 jQuery,我开始认为它阻碍了我想出一个解决方案。

What I am trying to do is have a check box that enables disabled radio buttons. If that makes sense.

我想要做的是有一个复选框来启用禁用的单选按钮。如果这是有道理的。

Example:

例子:

  • Choice 1
  • sub choice
  • sub choice
  • sub choice
  • 选择 1
  • 子选择
  • 子选择
  • 子选择

I would like to be able to click the first checkbox (Choice 1) to enable the sub choices. If it's not clicked, the sub choices should be disabled. :-)

我希望能够单击第一个复选框(选择 1)以启用子选项。如果未单击,则应禁用子选项。:-)

Here is what I've got so far:

这是我到目前为止所得到的:

<script>
function enableRadios(x) {
    var formElement = eval("checkbox" + x)
    if (formElement[0].disabled) {
        formElement[0].disabled = false
        formElement[1].disabled = false
    } else {
        formElement[0].disabled = true
        formElement[1].disabled = true
    }
 }</script>

<body><input type="checkbox" name="main" value="main" onClick="enableRadios(x)">
<input disabled type="radio" value="1" name="x">
<input disabled type="radio" value="2" name="x">
<input disabled type="radio" value="3" name="x">
<input disabled type="radio" value="4" name="x">
<input disabled type="radio" value="5" name="x">
<input disabled type="radio" value="6" name="x"></body>

I really appreciate your help!

我真的很感谢你的帮助!

回答by Samuel Liew

You need to pass a string containing the radio name 'x', not pass a variable x:

您需要传递一个包含收音机名称的字符串'x',而不是传递一个变量x

<script>
function toggleRadios(name) {
    var elems = document.getElementsByName(name);
    for(i=0; i<elems.length; i++) {
        elems[i].disabled = !elems[i].disabled;
    }
}
</script>

<input type="checkbox" name="main" value="main" onclick="toggleRadios('x')">
<input disabled type="radio" value="1" name="x">
<input disabled type="radio" value="2" name="x">
<input disabled type="radio" value="3" name="x">
<input disabled type="radio" value="4" name="x">
<input disabled type="radio" value="5" name="x">
<input disabled type="radio" value="6" name="x">

http://jsfiddle.net/samliew/B6tF7/

http://jsfiddle.net/samliew/B6tF7/