2012-04-13 35 views
0

我刚开始使用JavaScript,所以请原谅我,如果我的问题似乎很愚蠢。我想设计一个带有一些复选框的网页,当第一个复选框被选中时,其他复选框变为启用。我如何使用JS做到这一点?我写了下面的代码:使用Javascript启用复选框

function checkBox() { 
    if (window.document.form1.mainbox.checked=true) { 
     for (i=0;i<window.document.form1.Others.length;i++) { 
      window.document.form1.Others[i].disabled=false; 
     } 
    } 
    else { 
     for (i=0;i<window.document.form1.Others.length;i++) { 
      window.document.form1.Others[i].disabled=true; 
     } 
    } 
} 

而且这个网站:

<form name="form1"> 
<input name="mainbox" value="mainbox" onclick="checkBox()" type="checkbox"> Mainbox<br> 
<input disabled="disabled" checked="checked" tabindex="0" name="Others" type="checkbox">No. 1<br> 
<input disabled="disabled" checked="checked" tabindex="1" name="Others" type="checkbox"> No. 2<br> 
<input disabled="disabled" checked="checked" tabindex="2" name="Others" type="checkbox"> No. 3<br> 
</form> 

的问题是,在第一次点击其他复选框都被启用,但没有发生在随后的点击,即它们做不再被禁用。我该如何纠正这个问题?任何帮助将不胜感激。谢谢!

编辑

我跟着gabitzish的建议和它的工作。不过,我现在想通过其他的参数,所以我写:

<input name="mainbox" value="mainbox" onclick="checkBox(Others)" type="checkbox"> Mainbox<br> 

和修改脚本如下:

window.checkBox = function(chkname) { 
    if (window.document.form1.mainbox.checked==true) { 
     for (i=0;i<window.document.form1.chkname.length;i++) { 
      window.document.form1.chkname[i].disabled=false; 
     } 
    } 
    else { 
     for (i=0;i<window.document.form1.chkname.length;i++) { 
      window.document.form1.chkname[i].disabled=true; 
     } 
    } 
} 

但是,这是行不通的。请帮我在这里。我会非常感激。

回答

1

我创建了一个用的jsfiddle你的代码,以及一些细微的变化:http://jsfiddle.net/CUeDg/1/

原始代码的问题是checkBox()函数在点击时没有找到。

编辑: 这里是你的问题的后编辑的解决方案:http://jsfiddle.net/CUeDg/3/ 我已经通过参数去功能作为一个字符串。

后来编辑: 我怀疑你需要该参数来知道你需要切换哪些复选框。我也为此做了一个jsFiddle:http://jsfiddle.net/CUeDg/5/ (如果我怀疑有错,请不要考虑这部分答案)

+0

谢谢!这正是我想要的! – user828647 2012-04-13 12:39:58

+0

我编辑了我的答案,现在一个参数传递给您的函数 – gabitzish 2012-04-13 20:04:39

+0

您怀疑是正确的,并且您的解决方案有效!再次感谢,我已经接受你答案的承诺:) – user828647 2012-04-14 11:42:56

2

这一行有过错(您错过了=)

if (window.document.form1.mainbox.checked=true) 

尝试将其更改为

if (window.document.form1.mainbox.checked)