HTMLisEasy.com
HTML tutorials for the rest of us...
Javascript Tutor - Lesson 12

Another "built in" array is the options array in a drop down list. Consider the following list...

It's HTML is as follows:

<form name="form02">
<select name="bradykids">
<option value="greg">Greg
<option value="marsha">Marsha
<option value="peter">Peter
<option value="jan">Jan
<option value="bobby">Bobby
<option value="cindy">Cindy
</select>
</form>

Notice the list has a name (bradykids) and each option has a value.

Look at the following script...

<html>
<head>
<title></title>

<script type="text/javascript">

function GoBrady()
{
   brady = window.document.form02.bradykids.selectedIndex;
   alert(brady);
}

</script>

</head>
<body>

<form name="form02">
<select name="bradykids" onChange="GoBrady()">
<option value="greg">Greg
<option value="marsha">Marsha
<option value="peter">Peter
<option value="jan">Jan
<option value="bobby">Bobby
<option value="cindy">Cindy
</select>
</form>

</body>
</html>

Try it.

It uses the event handler onChange. When the state of the drop down list changes it invokes the function GoBrady(). This function throws up an alert box displaying the selectedIndex property of the options array. Fiddle with it until you understand what's going on.

Alrighty, we can easily get the index of the selected Brady. But, how can we get the value? Well, where the selectedIndex is a property of the options array, the values are properties of the individual options. Does that make sense?

Remember when we were looking at image arrays and we said that the first image in the array is images[0], the second is images[1] and so forth? Well, the options array is similar. We named our array bradykids, so the first option is bradykids[0], the second is bradykids[1], the third is bradykids[2], etc. In the last script we grabbed the selectedIndex and stored it in the variable brady. So, we could get properties of individual options with bradykids[brady]. Do I still have you or are you hopelessly confused? Have a look at this modified version of the last script...

<html>
<head>
<title></title>

<script type="text/javascript">

function GoBrady()
{
   brady = window.document.form02.bradykids.selectedIndex;
   alert(window.document.form02.bradykids[brady].value);
}

</script>

</head>
<body>

<form name="form02">
<select name="bradykids" onChange="GoBrady()">
<option value="greg">Greg
<option value="marsha">Marsha
<option value="peter">Peter
<option value="jan">Jan
<option value="bobby">Bobby
<option value="cindy">Cindy
</select>
</form>

</body>
</html>

Try it.

Keep studying it until you understand it.

<< BACK NEXT >>
Javascript Tutor
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Javascript Authoring Guide      JavaScript FAQ
HTML 4.0 Reference      Google Groups (Advanced Search)