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

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

If you find this site useful and are a book buyer/reader...

Abe Books is one of my affiliates. I only use affiliates that I also purchase products from. I love Abe books. I have purchased many books from them originally cost $40 to $60 for as little as $5 to $10 dollars including shipping costs.

By accessing Abe books and clicking on one of my links I receive a small commission on your purchase that helps pay for this site. You pay no more for your books than if you accessed their site directly. Thanks for your support.

I have found Javascript - The Good Parts to be an indespensible resource

Click on the book to find books on Javascript at Abe Books...

If you would like a new version of the book click below to buy it from Amazon (also one of my affiliates).

Javascript Examples

Basics

Forms

Misc













navTango.com free

75% of your donation

goes to charity.