2012-04-13 40 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)