2012-07-23 63 views
1

我有一個調用javascript函數的複選框。選中此複選框後,表單中的其他值將自動填寫。這些其他值的類型是另一個複選框和選項選擇字段。我在HTML如下:在javascript中自動填充表單完成

<div id="NA" > 
<input type="checkbox" name="remove_cd" value="r_on" id="r_on_cd" />N/A: 
<select name="reason" id="reason_list"> 
<option value="1">Option 1</option> 
<option value="2">Option 2</option> 
<option value="3">Option 3</option> 
</select> 
<font color="#cc0000">Reason Required</font><hr/></div> 

在JavaScript中,我見的功能如下:

... 
var y = document.getElementById("NA").children; 
for(var i=0; i<y.length; y++){ 
    y[i].checked=true; 
    y[i].options.selectedIndex=2; 
} 
... 

我有點困惑,爲什麼這是行不通的。當我點擊表格中的複選框時,<div id="NA">下的複選框被選中,但下拉列表中的選項不會被更改。想法?

+0

你能張貼的東西JSBin或的jsfiddle?您的代碼如何與您的標記匹配並不十分清楚。 – 2012-07-23 20:17:29

回答

2

你有y++,而不是在循環i++。試試這個

for(var i=0; i<y.length; i++){ 
    y[i].checked=true; 
    y[i].selectedIndex=2; 

} 

呼籲options.selectedIndex拋出Cannot set property 'selectedIndex' of undefined

+1

哇,我覺得自己像個白癡。不過謝謝。我累了。 – de1337ed 2012-07-23 20:39:47

0
y[i].options.selectedIndex=2; 

或許應該只是閱讀:

y[i].selectedIndex=2; 
+0

試過了,沒有工作 – de1337ed 2012-07-23 20:14:18

0

我不知道你想做什麼,但試試這個:

<div id="NA" > 
<input type="checkbox" name="remove_cd" value="r_on" id="r_on_cd" />N/A: 
<select name="reason" id="reason_list"> 
<option value="1">Option 1</option> 
<option value="2">Option 2</option> 
<option value="3">Option 3</option> 
</select> 
<font color="#cc0000">Reason Required</font><hr/></div> 
<script> 
    window.onload = function() { 
     var y = document.getElementById("NA").children; // it's not a good idea to use children array, because if you add a new element in the begining your script will fail 
     var checkbox = y[0]; // it is better here to use: document.getElementById('r_on_cd'); 
     var select = y[1]; // it is better here to use: document.getElementById('reason_list'); 
     checkbox.onclick = function() { 
      select.options.selectedIndex = 2; 
     }; 
    } 
</script>