简体   繁体   English

使用javascript启用和禁用复选框

[英]Enabling and disabling checkboxes with javascript

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. 我仍然是Javascript的新手,所以如果我听起来很愚蠢,请原谅我。 Sadly I don't know jQuery and I'm starting to think that it's inhibiting me to come up with a solution. 可悲的是,我不知道jQuery,我开始认为它阻止我提出一个解决方案。

What I am trying to do is have a check box that enables disabled radio buttons. 我想要做的是有一个复选框,启用禁用单选按钮。 If that makes sense. 如果这是有道理的。

Example: 例:

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

I would like to be able to click the first checkbox (Choice 1) to enable the sub choices. 我希望能够单击第一个复选框(选项1)以启用子选项。 If it's not clicked, the sub choices should be disabled. 如果未单击,则应禁用子选项。 :-) :-)

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! 我真的很感谢你的帮助!

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM