سؤال

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

If I select apple from the first drop down, only the options

  • "is sometimes green",
  • "is sometimes blood red",
  • "is sometimes sour"

should be available. Others should be removed/hidden. I am looking for a JavaScript only solution; I don't know jQuery.

هل كانت مفيدة؟

المحلول

A javascript only demo to change option of a select tested in chrome 31 and IE11.

This html attaches the function setOption to the onchange-event. According to quirksmode the change event is buggy. So you might have to fix / expand to improve cross browser compatibility.

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

This javascript changes the options of the second select s2 after the selected option of the first select s1 was changed - the onchange-event was fired:

 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"]);
    }
  }

And to add options

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

This function might need be be enhanced as well to improve cross browser compabillity.

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

See the fully working demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top