Drop Down Selection Lists


Level: Basic
Skills Required: JavaScript Functions and HTML Forms


Abstract:

A selection list is similar to a group of radio buttons - a user can select an option from the several available. People use a selection list in place of radio buttons when the number of options is large. But the real power is attained by manipulating the selection list via JavaScript.

JavaScript allows us to add and remove elements from selection lists dynamically. We can also make decisions on the basis of current selection. The lines that follow will explain the implementation of a JavaScript based navigational menu. The visitor is displayed a drop down selection list and taken to a related page when a selection is made.

Ground Work:

We will start with a simple example before jumping to the targeted code. First of all, let's review the syntax used to make an HTML selection list (no JavaScript involved):

<form name="example">
<select name="numbers">
<option>Number 1
<option>Number 2
<option>Number 3
<option>Number 4
<option>Number 5
</select>
</form>

The above code will create a drop down selection list having 5 options available: Number 1 to Number 5. We have a left a lot of optional things; assuming that you know this stuff.

Getting Into It:

Now let's write a function that tells you what number you have selected from this list. Keep in mind the JavaScript hierarchy: a selection list is contained in a form which in turn is contained in the document object. The following function, Say(), is invoked whenever a button is clicked. This function checks the current selection and displays an appropriate message.

function Say()
{
   switch (document.example.numbers.selectedIndex)
   {
      case 0: alert ("One"); break;
      case 1: alert ("Two"); break;
      case 2: alert ("Three"); break;
      case 3: alert ("Four"); break;
      case 4: alert ("Five"); break;
      default: alert ("Error"); break;
   }
}


Selection Object:

The selection object used above is named "numbers" and its defined in a form named "example". From JavaScript we can access and manipulate the selection list using document.example.numbers.propertyName. One of the properties of the selection list is selectedIndex, which gives the number of the selected item. Like C++ and Java, arrays in JavaScript start with 0 index. This means that the first item is numbered 0 and the last one n-1.


Switch Statement:

Switch statements are a way to avoid cumbersome multiple if-then-else constructs. In the above example we have to take 5 different actions depending on the 5 different values of the selected item. We can handle that by using something like

The copyright of the article Drop Down Selection Lists in JavaScript is owned by Muhammad Ali Shah. Permission to republish Drop Down Selection Lists in print or online must be granted by the author in writing.

Go To Page: 1 2 3

Articles in this Topic    Discussions in this Topic