In Action

Synchronized Dropdown Menus

This javascript populates a dropdown menu box based upon the user selection in another dropdown menu. It is fairly generic code and can be readily expanded upon or used more dynamically in Php generated webpage code.

Javascript in Action


Parent Dropdown Menu:
Child:


Javascript Code

Javascript Code

Javascript and html code are self contained below.

     
<script language="javascript"> 
var syncDDM1 = new Array("Apple", "Orange", "Kiwi", "Grapes");
var syncDDM2 = new Array("Potato", "Carrot", "Lettuce");

function getDDMvals() {
  var select_parent = document.myform.parentDDM ;
  var select_vals = document.myform.dropDownItems;
  var parent_val = select_parent.options[select_parent.selectedIndex].value;

  select_vals.options.length=0;
  if (parent_val == "a")
  {
    for(var i=0; i<syncDDM1.length; i++)
    select_vals.options[select_vals.options.length] = 
    new Option(syncDDM1[i]);
  }
  if (parent_val == "b")
  {
    for(var i=0; i<syncDDM2.length; i++)
    select_vals.options[select_vals.options.length] = 
    new Option(syncDDM2[i]);
  }
}
</script>

HTML Code

HTML Code



<form name="myform" method="POST">
  <table>
    <tr>
    <td>Parent Dropdown Menu:</td><td>
    <select name="parentDDM" onchange="getDDMvals()">
    <option>
    <option value="a">Fruit
    <option value="b">Vegetables
    </select></td></tr>
    <tr>
    <td>Child:</td><td>
    <select name="dropDownItems">
    <option>
    </select></td></tr>
  </table>
</form>