Using the options array to access elements within the list
Using the above list as an example, with values added in for each element:
<form name="George"> <p><select name="example" size="1"> <option value="1">choice1</option> <option value="2">choice2</option> <option value="3">choice3</option> <option value="4">choice4</option> </select></p> </form>
Ok, lets assume we want to access the first element of this selection list:
document.George.example.options //gives us access to element "choice1"
This will give us direct access to the first element of the selection list.
To access the third element, we would do this:
document.George.example.options //gives us access to element "choice3"
And to access the final element, we would do this:
document.George.example.options //gives us access to element "choice4"
It doesn't take a rocket scientist to realize that the number inside the [ ] are always "1" minus the actual position of the element in the list. ALL ARRAYS BEGIN WITH INDEX NUMBER "0", NOT "1"
So, now that we know the way to get to these little rats, lets see some properties we can use with them:
Lets say we want to alert the name of the first element (in this case, the name is "choice1"):
And lets say we want to know the value that's associated with this element:
I know selection lists are a mess, but that's the way they are accessed...
We now know how to access each of the elements within the selection list...but only by hard-coding the index number into the script. For example, we still have no way of telling our script to alert the value of each element, depending on what he/she has selected. We will now proceed to learn how we can have scripts automatically update itself whenever a different selection is made by the user, and see some practical uses of this.