Main Page

Removing options

oOption.setAttribute(“value”, sValue);
}
oListbox.appendChild(oOption);
}
This method can be used like this:
var oListbox = document.getElementById(“selListbox”);
ListUtil.add(oListbox, “New Display Text”); //add option with no value
ListUtil.add(oListbox, “New Display Text 2”, “New value”); //add option with value
Removing options
JavaScript provides the capability to not only add options, but to remove them as well. There is an old
way of removing an option from a list box, which is simply to use the
options
collection and set the
option in question to be equal to
null
:
oListbox.options[1] = null;
Once again, this is BOM functionality; things can be done in a much more logical sense using the HTML
DOM, which provides a
remove()
method for the
<select/>
element. You just pass in the index of the
option to remove:
var oListbox = document.getElementById(“selListbox”);
oListbox.remove(0); //remove the first option
If you are so inclined, you may choose to wrap this into a
ListUtil
method so that you can do both add
and remove the same way:
ListUtil.remove = function (oListbox, iIndex) {
oListbox.remove(iIndex);
}
The code can then be rewritten like this:
var oListbox = document.getElementById(“selListbox”);
ListUtil.remove(oListbox, 0); //remove the first option
If you want to remove all the options in a list box, you can just call
remove()
on each option:
ListUtil.clear = function (oListbox) {
for (var i=oListbox.options.length-1; i >= 0; i--) {
ListUtil.remove(oListbox, i);
}
};
360
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 360


JavaScript EditorFree JavaScript Editor     Ajax Editor


©