依赖下拉选择

时间:2015-06-24 10:14:30

标签: javascript ajax

  1. 标准选择

  2. 部分选择

  3. 主题选择

  4. 选择取决于其他部分取决于standard.subject取决于部分 如果我选择主题,则仅显示主题分配

1 个答案:

答案 0 :(得分:0)

通常,当您需要根据下拉列表进行更改时,请使用onchange事件。例如:

<select id="standardSelectId" onchange="fillSection(this)">...</select>
<select id="sectionSelectId" onchange="fillSubject(this)"><option>-- Select Standard first --</option></select>
<select id="subjectSelectId"><option>-- Select Section first --</option></select>

然后,编写一个javascript函数来填充下一个选项,并清除任何依赖于下一个选择的选择:

<script type="text/javascript">
function fillSection(e) {
  var choice = e.options[e.selectedIndex];
  var sectionSelect = document.getElementById("sectionSelectId");
  var subjectSelect = document.getElementById("subjectSelectId");
  subjectSelect.options.length = 0;
  try { subjectSelect.add(new Option("-- Select Section first --", ""))} catch(ex) {subjectSelect.add(new Option("-- Select Section first --", ""), null)}
  sectionSelect.options.length = 0;
  switch (choice.value) {
    case <standard val1>:
      try { sectionSelect.add(new Option(section1_label_1, section1_key_1))} catch(ex) {subjectSelect.add(new Option(section1_label_1, section1_key_1), null)}
      ...
      try { sectionSelect.add(new Option(section1_label_N, section1_key_N))} catch(ex) {subjectSelect.add(new Option(section1_label_N, section1_key_N), null)}
      break;
    case <standard valX>:
      try { sectionSelect.add(new Option(sectionX_label_1, sectionX_key_1))} catch(ex) {subjectSelect.add(new Option(sectionX_label_1, sectionX_key_1), null)}
      ...
      try { sectionSelect.add(new Option(sectionX_label_N, sectionX_key_N))} catch(ex) {subjectSelect.add(new Option(sectionX_label_N, sectionX_key_N), null)}
      break;
  }
  function fillSubject(e) {
    ...
  }