2013-07-10 99 views
0

我有一個動態的下拉框,當我選擇一個酒店,它帶出了相應的日期。現在我想在一個單獨的下拉列表中添加時間。我嘗試在函數中添加另一個參數,但沒有成功。例如,如果我圖片中情局,它會顯示日期10/09/13和11/09/13在下拉日期。現在我想在其自己的下拉菜單中添加19:00和18:00的時間選擇。Javascript:動態下拉框更新

<script type="text/javascript"> 
function populate(s1,s2){ 
var s1 = document.getElementById(s1); 
var s2 = document.getElementById(s2); 
s2.innerHTML = ""; 
if(s1.value == "CIA to Table Bay Hotel" || s1.value == "CIA to The Portswood Hotel" || s1.value == "CIA to The Commodore Hotel" || s1.value == "CIA to Victoria and Alfred Hotel"){ 
var optionArray = ["-1|Pick a date","10/09/13|10/09/13","11/09/13|11/09/13"]; 
} else if(s1.value == "Table Bay Hotel to CIA" || s1.value == "The Portswood Hotel to CIA" || s1.value == "The Commodore Hotel to CIA" || s1.value == "Victoria and Alfred Hotel to CIA"){ 
var optionArray = ["-1|Pick a date","14/09/13|14/09/13","15/09/13|15/09/13"]; 
} 
for(var option in optionArray){ 
var pair = optionArray[option].split("|"); 
var newOption = document.createElement("option"); 
newOption.value = pair[0]; 
newOption.innerHTML = pair[1]; 
s2.options.add(newOption); 
} 
} 
</script> 

<tr> 
<td>&nbsp;</td> 
<td><span class="style1"><span class="style7">*</span>Transfer?</span></td> 
<td><select id="where" name="where" onChange="populate(this.id,'date')"> 
<option value="Pick up point">Pick up point</option> 
<option value="CIA to Table">CIA to Table Bay Hotel</option> 
<option value="CIA to Portswood ">CIA to The Portswood Hotel</option> 
<option value="CIA to Commodore">CIA to The Commodore Hotel</option> 
<option value="CIA to Victoria and Alfred Hotel">CIA to Victoria and Alfred Hotel</option> 
<option value="Table to CIA">Table Bay Hotel to CIA</option> 
<option value="Portswood to CIA">The Portswood Hotel to CIA</option> 
<option value="Commodore to CIA">The Commodore Hotel to CIA</option> 
<option value="Victoria and Alfred Hotel to CIA">Victoria and Alfred Hotel to CIA</option> 
</select></td> 
</tr> 

<tr> 
<td>&nbsp;</td> 
<td><span class="style4"><span class="style7">*</span>Which Date? </span></td> 
<td><select id="date" name="date"></select></td> 
</tr> 

<tr> 
<td>&nbsp;</td> 
<td><span class="style4"><span class="style7">*</span>Time? </span></td> 
<td><select id="time" name="time"></select></td> 
</tr> 

回答

0

那麼..那JavaScript代碼寫得不好。

但要回答你的問題,並繞過它。

onChange="propulate(this.id, 'date', 'time')" 

function populate(s1, s2, s3) { 
    ... 
    var s3 = document.getElementById(s3); 
    s3.innerHTML = ''; 
    ... 
    if (s1.value == ...) { 
    timeOptionArray = ["-1|Pick a time", "19:00|19:00", "18:00|18:00"]; 
    } 
    ... 
    for (var option in timeOptionArray) { ... } 

這將是你的代碼的補充,而不是替代品。

一對夫婦建議:

  • 提供一個更好的名字,以S1,S2,像transferSelectIddateSelectId
  • 不要聲明具有相同的名稱作爲populate函數中的參數變量,所以他們的名字transferSelectdateSelect
  • 聲明if條件外optionArray變量,只有做一次
  • 現在,你有日期和時間,這將會被填充以同樣的方式,提取方法來填充他們(EG)function populateSelect(node, options) { ... }其設置innerHTML來清空並創建選項。