January 12, 2002 - Related Menus | WebReference

January 12, 2002 - Related Menus

Yehuda Shiran January 12, 2002
Related Menus
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

The Menu Builder tool under the Cool Tools section of http://www.docjs.com lets you build a set of related manus. Go ahead and play around with the tool. If we take just two menus, and trim down the URL display functionality, we'll end up with something like this:

As you can see, there are three entries in each menu. Change the selected option on the left menu, and see how the right manu changes automatically. Here is the HTML code:

<FORM NAME="menu">
<SELECT NAME="topics" onChange="relate(this.form)">
<OPTION VALUE="">level2
<OPTION VALUE="">level3
<SELECT NAME="list">
<OPTION VALUE="">level12
<OPTION VALUE="">level13
We have two menus, topics and list. An event handler, onChange, triggers a change in list when topics changes. The idea is to display in list options that are related to the selected option in topics. Here is the JavaScript code:

  var ar = new Array();
  ar[0] = new Array();
  ar[0][0] = new makeOption("level11");
  ar[0][1] = new makeOption("level12");
  ar[0][2] = new makeOption("level13");
  ar[1] = new Array();
  ar[1][0] = new makeOption("level21");
  ar[1][1] = new makeOption("level22");
  ar[1][2] = new makeOption("level23");
  ar[2] = new Array();
  ar[2][0] = new makeOption("level31");
  ar[2][1] = new makeOption("level32");
  ar[2][2] = new makeOption("level33");
function makeOption(text) {
  this.text = text;
function relate(form) {
  var options = form.list.options;
  for (var i = options.length - 1; i > 0; i--) {
    options[i] = null;
  var curAr = ar[form.topics.selectedIndex];
  for (var j = 0; j < curAr.length; j++) {
    options[j] = new Option(curAr[j].text);
  options[0].selected = true;
// -->
The first section defines the arrays of options. The relate() function initializes list's options to null, and then creates the related list menu, according to the selected topics' options.

To read more about related menus, be sure to visit Webreference.com's tutorial.