↑
Main Page
getSelectedIndexes
It is possible, however, to select more than one option in a list box (but not in a combo box) by setting the
multiple
attribute of the
<select/>
element to
“multiple”
:
<select name=”selAge” id=”selAge” size=”3” multiple=”multiple”>
<option value=”1”>18-21</option>
<option value=”2”>22-25</option>
<option value=”3”>26-29</option>
<option value=”4”>30-35</option>
<option value=”5”>Over 35</option>
</select>
If multiple options are selected,
selectedIndex
contains the index of the first selected item, but that
really doesn’t help. What you need is a way to get the indexes of all the selected options. For this, you
need a custom method, which is the first for the
ListUtil
object.
The
getSelectedIndexes()
method takes advantage of another special property of the
<option/>
element: the
selected
property. The HTML DOM defines the
selected
property as a Boolean value
indicating whether the individual option is selected. So, all that is necessary is to loop through the
options of a list box and test to see if they are selected or not. If so, you need to save that index into an
array that will ultimately hold the indices of all selected options.
This method needs only one argument, the list box to check:
ListUtil.getSelectedIndexes = function (oListbox) {
var arrIndexes = new Array;
for (var i=0; i < oListbox.options.length; i++) {
if (oListbox.options[i].selected) {
arrIndexes.push(i);
}
}
return arrIndexes;
};
The
getSelectedIndexes()
method can then be used to either retrieve the indexes of the selected
options or, using the length of the returned array, to determine how many options are selected:
var oListbox = document.getElementById(“selListbox”);
var arrIndexes = ListUtil.getSelectedIndexes(oListbox);
alert(“There are “ + arrIndexes.length + “ option selected.”
+ “The options have the indexes “ + arrIndexes + “.”);
This code first gets a reference to the list box with the ID
“selListbox”
and then retrieves the selected
indexes and stores them in
arrIndexes
. The alert displays the a message indicating the number of
selected options as well as displaying their indexes (remember, the
toString()
method of an
Array
object returns all items in a comma-separated string).
358
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 358
Free JavaScript Editor
Ajax Editor
©
→