↑
Main Page
Accessing options
Because both controls use the same HTML code, it’s possible to manipulate them using the same
JavaScript code. Naturally, the first step to manipulating either is to get a reference from the document
either by using
document.getElementById()
or accessing it in the
document.forms
collection:
oListbox = document.getElementById(“selAge”);
oListbox = document.forms[“form1”].selAge;
oListbox = document.forms[0].selAge;
For this section, the methods you create are all attached to a common object called
ListUtil
, in order to
keep them straight (similar to the
EventUtil
object created earlier in the book).
ListUtil
is just a sim-
ple object to which the methods are attached:
var ListUtil = new Object();
Accessing options
The HTML DOM defines each
<select/>
element to have a collection called
options
, which is the list
of all
<option/>
elements for the control. To get the display text and value of an
<option/>
, you can
use normal DOM functionality:
alert(oListbox.options[1].firstChild.nodeValue); //output display text
alert(oListbox.options[1].getAttribute(“value”)); //output value
However, it is easier to use two special
<option/>
properties that are defined in the HTML DOM:
text
,
which returns the display text, and
value
, which returns the value attribute. These two properties are
provided for backwards compatibility with older BOM functionality used to manipulate options.
alert(oListbox.options[1].text); //output display text
alert(oListbox.options[1].value); //output value
Each
<option/>
also has an
index
property, indicating its position in the
options
collection:
alert(oListbox.options[1].index); //outputs “1”
Of course, because
options
is a collection, you can use its length property to determine how many
options exist:
alert(“There are “ + oListbox.options.length + “ in the list.”);
But how do you know which option is currently selected?
Retrieving/changing the selected option(s)
The
<select/>
element has an attribute,
selectedIndex
, which always contains the index of the cur-
rently selected option (or –1 if no options are selected).
alert(“The index of the selected option is “ + oListbox.selectedIndex);
357
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 357
Free JavaScript Editor
Ajax Editor
©
→