↑
Main Page
Adding options
Adding options
If you don’t load any options into a list box or combo box using HTML, you can do so using JavaScript.
To start, define a method with three arguments: the list box to work on, the name of the option to add,
and the value of the option to add.
ListUtil.add = function (oListbox, sName, sValue) {
//...
}
Next, create an
<option/>
element using the DOM methods and assign the option name by creating a
text node:
ListUtil.add = function (oListbox, sName, sValue) {
var oOption = document.createElement(“option”);
oOption.appendChild(document.createTextNode(sName));
//...
}
The option value is actually not required, so you should only add it if the argument has been passed in.
To do this, ensure that
arguments.length
is equal to 3, and if so, set the
value
attribute:
ListUtil.add = function (oListbox, sName, sValue) {
var oOption = document.createElement(“option”);
oOption.appendChild(document.createTextNode(sName));
if (arguments.length == 3) {
oOption.setAttribute(“value”, sValue);
}
//...
}
The last step is to add the new option to the list box by using the
appendChild()
method:
ListUtil.add = function (oListbox, sName, sValue) {
var oOption = document.createElement(“option”);
oOption.appendChild(document.createTextNode(sName));
if (arguments.length == 3) {
Even though intended for multiple-selection list boxes, the
getSelectedIndexes()
method works in both single-selection list boxes and combo boxes, returning an
array with only one item: the value of
selectedIndex
.
359
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 359
Free JavaScript Editor
Ajax Editor
©
→