Free Javascript Tutorials

home

JavaScript Tutorials

Form Validation continued

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

Using JavaScript to Validate a Drop Down Box

 

A drop down box on a form allows you to select one option among many. It looks like this:

Here's the HTML code for the above drop down box:


<SELECT NAME = s1>
<OPTION VALUE = "NE" selected >North East</OPTION>
<OPTION VALUE = "NW">North West</OPTION>
<OPTION VALUE = "SE">South East</OPTION>
<OPTION VALUE = "SW">South West</OPTION>
<OPTION VALUE = "Midlands">Midlands</OPTION>
</SELECT>

Notice the NAME of our Select box (as the drop down box is called in HTML world). The NAME we've chosen is s1. The name of our form is f1. So here's a function that gets which item the user selected:

function GetSelectedItem() {

len = document.f1.s1.length
i = 0
chosen = "none"

for (i = 0; i < len; i++) {
if (document.f1.s1[i].selected) {
chosen = document.f1.s1[i].value
}
}

return chosen
}

The code is similar to the check box code. We set the length of the select box (length is how many items in the list, minus 1 item):

len = document.f1.s1.length

Then inside the loop, we again access the index number of the SELECT object:

document.f1.s1[i].selected

So, s1[0] is the first item in the list, s1[1] the second item, s1[2] the third, and so on.

Once the selected item has been detected, you access it's value property and pop it into a variable:

chosen = document.f1.s1[i].value

You can test out the script by selecting an item from the box below.

What we've done with this box is to add an event to the select box. The event calls the function:

<SELECT NAME = s1 onChange = GetSelectedItem()>

In the next part, we'll see how to get at which items have been selected in a list box.

Move on to the Next Part-->

<--Back to the JavaScript Contents Page