Java Reference
In-Depth Information
with the Select object. For instance, in the preceding example, if the <select/> element was contained
in a form called theForm with the following:
document.theForm.theDay.options[0]
you would access the option created for Monday.
How can you tell which option has been selected by the user? Easy: You use the Select object's
selectedIndex property. You can use the index value returned by this property to access the selected
option using the options collection.
The Option object also has index, text, and value properties. The index property returns the index
position of that option in the options collection. The text property is what's displayed in the list, and
the value property is the value defi ned for the option, which would be posted to the server if the form
were submitted.
If you want to fi nd out how many options there are in a select element, you can use the length prop-
erty of either the Select object itself or of its options collection property.
Let's see how you could loop through the options for the preceding select box:
var theDayElement = window.document.form1.theDay;
document.write(“There are “ + theDayElement.length + “options<br />”);
var optionCounter;
for (optionCounter = 0; optionCounter < theDayElement.length; optionCounter++)
{
document.write(“Option text is “ +
theDayElement.options[optionCounter].text)
document.write(“ and its value is “);
document.write(theDayElement.options[optionCounter].value);
document.write(“<br />“)
}
First, you set the variable theDayElement to reference the Select object. Then you write the number of
options to the page, in this case 7.
Next you use a for loop to loop through the options collection, displaying the text of each option,
such as Monday, Tuesday, and so on, and its value, such as 0, 1, and so on. If you create a page based on
this code, it must be placed after the <select/> element's defi nition.
It's also possible to add options to a select element after the page has fi nished loading. You'll look at
how this is done next.
Adding and Removing Options
To add a new option to a select element, you simply create a new Option object using the new operator
and then insert it into the options collection of the Select object at an empty index position.
When you create a new Option object, there are two parameters to pass: The fi rst is the text you want to
appear in the list, and the second the value to be assigned to the option.
var myNewOption = new Option(“TheText”,”TheValue”);
Search WWH ::




Custom Search