Main Page

Moving Options

This method removes all options by iterating in reverse order. This is necessary because every time an
option is removed, the
index
property of each option is reset to the proper position. For this reason, it is
always best to remove the option with the highest index first and work your way back to the option with
the lowest index. Otherwise, you must keep track of multiple changing indexes.
Moving Options
In early JavaScript, moving options from one list box to another was a rather arduous process that
involved removing the option from the first list box, creating a new option with the same name and value,
then adding that new option to the second list box. Fortunately, the DOM provides a much more concise
way of doing things. Using DOM methods, it’s possible to literally move an option from the first list box
into the second list box by using the
appendChild()
method. If you pass an element that is already in the
document into this method, the element is removed from its parent and put into the position specified.
The method to execute this functionality accepts three arguments: the list box that the option currently
resides in, the list box to move the option to, and the index of the option to move. The method can then
take the option in the given index (assuming it exists) and move it to the second list box:
ListUtil.move = function (oListboxFrom, oListboxTo, iIndex) {
var oOption = oListboxFrom.options[iIndex];
if (oOption != null) {
oListboxTo.appendChild(oOption);
}
}
It is then possible to move a given option from one list box to another by using code such as the
following:
var oListbox1 = document.getElementById(“selListbox1”);
var oListbox2 = document.getElementById(“selListbox2”);
ListUtil.move(oListbox1, oListbox2, 0); //move the first option
This code moves the first option from
oListbox1
into
oListbox2
(the new option appears at the
bottom of
oListbox2
).
Reordering options
To reorder options in a list box, moving a particular option either up or down, two methods are neces-
sary, one to shift an option up and one to shift an option down. Each method takes two arguments: the
list box to act on and the index of the option to move. Both also make use of the DOM
insertBefore()
method to reorder the
<option/>
elements.
Moving options is the same as removing them in that the
index
property of each
option is reset into the proper position, so you should always move the option with
the highest index first.
361
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 361


JavaScript EditorFree JavaScript Editor     Ajax Editor


©