Javascript:动态下拉框更新

时间:2013-07-10 18:32:25

标签: javascript drop-down-menu

当我选择酒店时,我有一个动态下拉框,显示相应的日期。现在我想在单独的下拉列表中添加时间。我尝试在函数中添加另一个参数但没有成功。例如,如果我拍摄CIA,它将在下拉日期显示日期10/09/13和11/09/13。现在我想在19:00和18:00添加时间选择。

<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>

1 个答案:

答案 0 :(得分: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
  • optionArray条件之外声明if变量,只执行一次
  • 现在你有了以相同的方式填充的日期和时间,提取一个方法来填充它们(例如)function populateSelect(node, options) { ... },它将innerHTML设置为空并创建选项。