根据第一个下拉选项更改第二个下拉选项(仅限JavaScript)

时间:2014-05-04 08:06:59

标签: javascript html options

鉴于此html:

<select id="fruits" name="fruits">
  <option selected>Please select a fruit</option>
  <option>Apple</option>
  <option>Mango</option>
  <option>Banana</option>
</select>
<select id="options" name="options">
  <option selected>--Select a fruit first--</option>
  <option>is sometimes green</option>
  <option>is sometimes yellow</option>
  <option>is sometimes blood red</option>
  <option>is sometimes sour</option>
  <option>is sometimes sweet</option>
  <option>is sometimes bitter</option>
</select>

如果我从第一个下拉菜单中选择苹果,只选择

选项
  • &#34;有时是绿色&#34;,
  • &#34;有时是血红色&#34;,
  • &#34;有时是酸的&#34;

应该可用。其他人应该被删除/隐藏。 我正在寻找一个JAVASCRIPT ONLY解决方案;我不认识jQuery!

请帮忙!

1 个答案:

答案 0 :(得分:1)

在chrome 31和IE11中测试 javascript only demo to change option of a select

此html将函数setOption附加到onchange - 事件。根据quirksmode the change event is buggy 。因此,您可能必须修复/扩展以提高跨浏览器兼容性。

<select id="s1" onchange="setOptions()">
  <option>Pizza</option>
  <option>Pasta</option>
  <option>HotDogs</option>
</select>
<select id="s2">
  <option>Pizza 1</option>
  <option>Pizza 2</option>
  <option>Pizza 3</option>
</select>

在第一个选择s2的所选选项发生更改后,此javascript会更改第二个选择s1的选项 - onchange-event被触发:

 function setOptions()
  {        
    document.getElementById('s2').options.length = 0; // remove all options

    var selIndex = document.getElementById("s1").selectedIndex;
    if(selIndex == 0)
      addAllOptions('s2', ["Pizza Diavolo","Pizza Veggie"]);
    else if(selIndex == 1){
      addAllOptions('s2', ["Pasta Napoli","Pasta Primavera"]);
    }
    else{
      addAllOptions('s2', ["Hot Dog Chilie King","Hot Dog Silent Wiener"]);
    }
  }

并添加选项

 function addAllOptions(selectID, values)
  {
    var arrayLength = values.length;
    for (var i = 0; i < arrayLength; i++) {
        appendOptionLast(selectID,values[i]);
    }
  }

此功能可能还需要增强,以提高跨浏览器的兼容性。

  // see http://www.mredkj.com/tutorials/tutorial005.html      
  function appendOptionLast(selectID, num)
  {
    var elSel = document.getElementById(selectID);        
    var elOptNew = document.createElement('option');
    elOptNew.text = num;
    elOptNew.value = 'a_' + num;

    try {
      elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew); // IE only
    }
  }

请参阅 fully working demo