PROPERTY: Select::options
object.options
The options property is an array of all the options in a particular Select object. There is one
element (numbered in ascending order from zero) for each <OPTION> tag. You can use the length
property of this array to refer to the number of options in a particular Select object as follows:
Code:
document.myForm.mySelect.options.length
...or by simply using the length property of the Select object:
Code:
document.myForm.mySelect.length
You can use the options array to add options to, or delete options from
any Select object. When adding or altering an option, you assign an
Option object
to a particular element of the array. The following code first creates an Option object
called Folk, and then assigns it to element # 3 of the options array of a user-defined
Select object called MusicType. If there is a value already assigned to element 3, it
will be replaced by Folk, otherwise it will be created along with undefined elements at every
index between the one created and the last existant one.
Code:
document.forms[0].musicType.options[3] = new Option("Folk", "folk", false, false)
Similarly, you can delete any option by assigning the value null to the appropriate
element of the options array:
Code:
document.forms[0].musicType.options[2] = null
This will have the effect of removing element # 2 from the options array, and at the same
time compressing the array so that element # 3 becomes # 2, element # 4 becomes # 3 etc.
After deleting an option you must refresh the document by using history.go(0) at the
end of the code. To determine which option of a Select object is currently selected, you
can use the selectedIndex property along with the options property as follows:
Code:
document.forms[0].musicType.options.selectedIndex
...or you could simply use the selectedIndex property of the Select object:
Code:
document.forms[0].musicType.selectedIndex
Both the above lines of code return the number of the currently-selected index. If, however,
the Select object allows for multiple selections (i.e. when the <SELECT> tag
includes the MULTIPLE attribute), the selectedIndex property will only return the index
of the first option selected. To determine all of the selected options, you would have to loop
through the options array testing each option individually.
|