Java Reference
In-Depth Information
If you want to find out how many options are in a select element, you can use the
length
property
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 = document.theForm.theDay;
document.write("There are " + theDayElement.length + "options<br />");
for (var index = 0; index < theDayElement.length; index++) {
document.write("Option text is " +
theDayElement.options[index].text);
document.write(" and its value is ");
document.write(theDayElement.options[index].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 definition.
It's also possible to add options to a select element after the page has finished loading. You look at
how to do this 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, you have two parameters to pass. The first is the text you
want to appear in the list, and the second is the value to be assigned to the option:
var myNewOption = new Option("TheText","TheValue");
You then simply assign this
Option
object to an empty array element. For example:
theDayElement.options[0] = myNewOption;
If you want to remove an option, you simply set that part of the
options
collection to
null
. For
example, to remove the element you just inserted, you need the following:
theDayElement.options[0] = null;
When you remove an
Option
object from the
options
collection, the collection is reordered so that
the array index value of each of the options above the removed one has its index value decremented
by one.
When you insert a new option at a certain index position, be aware that it will overwrite any
Option
object that is already there.