Dual List Box Example
See a working example of this code Full Code Back to Tutorials
In this example we look a fairly common tool, dual list boxes. This is when you have two list boxes with the option to move items from one box to the other. This example utilizes an array to add the available options to the left list box. Normally the options would be selected from a database along with their values. Here we arbitrarily assign values in the order they appear in the array.
This example is mostly Javascript. The only ASP code is for creating the original options in the left list box, and for displaying the results when the page is submitted.
Some of the things we see in this example are adding and removing options from a list box; sorting the entries of a list box, and moving entries in a list box up or down in the list. We also see how to deal with listboxes that have multiple select turned on.
List boxes are really just a varient of a drop-down list. The only difference from the programming perspective is that a listbox has a defined height where the drop-down list has a height of only one row except when opened. This makes for a completely different appearing element, but symantically they are the same. A list box is defined by using the <select> HTML element. Between the opening and closing tags of the select element are option elements that define the options in the list. The list box has several properties that allow us to manipulate it with JavaScript.
options.length - Gives the number of options in the list box
options[option index].value - The value of the specified option
options[option index].innerHTML - The text of the specified option
options[option index].selected - True if the specified option is selected
selectedIndex - The index number of the selected option
Note if multiple options are selected that selectedIndex will return 0
Using the above properties we can look at how we add an option to a list box.
First, we have to have a list box defined in the page. The following code will
create two listboxes sized to display 10 items at once. The first box has an ID of
'availableItems' ans is loaded with items. The second box has no options loaded.
<select id='availableItems' size='10'> <option value='0'>Apples</option> <option value='1'>Oranges</option> <option value='2'>Grapes</option> <option value='3'>Berries</option> <option value='4'>Kiwis</option> </select> <select id='selectedItems' size='10'> </select>
Adding an Option
Adding an option to the end of the listbox requires that we know the current length of the listbox. As mentioned above Javascript has just the thing: options.length
// set a variable to the listbox object for easier referencing.
var ai = document.getElementById('availableItems');
var opt = ai.options.length; // # of options
The options array is zero based. This means that using the above code where the variable ai is assigned to the list box object, the first option is ai.options[0] not ai.options[1]. So if there are 5 options, the last option is ai.options[4] but the value of ai.options.length though will be 5. This is important, because when we add an option we need to specify what option number to add. The way to add a new option is with ai.option[option#] = new Option(option Text, option Value);
Since the value of ai.options.length is always 1 more than the index for the last option we can always use the length of the options array to as our index to add an option to the end of a list box. In the above code we assigned the variable opt to the value of the length of the options array. Using this we can use the following code to add Bananas to the list box.
ai.options[opt] = new Option("Bananas","5")
Removing an Option
Removing an option from a listbox is very easy. All we need to do is set the option to null. This will reindex the remaining items in the listbox so that they align to their new position in the list box. For example if we wanted to remove Grapes, which is the thired option in the list box then we would use the following code:
ai.options[2] = null;
Note that we used the index 2 instead of 3. This is because, as mentioned above, the options array is zero based. Before running this command we have this information in the options array.
Before Running Command | After Running Command
Index Text Value | Index Text Value
===== ========= ====== | ===== ========= ======
0 Apples 0 | 0 Apples 0
1 Oranges 1 | 1 Oranges 1
2 Grapes 2 | 2 Berries 3
3 Berries 3 | 3 Kiwis 4
4 Kiwis 4 |
Moving an Option from One List box to Another
There are several ways that an option can be moved from one list box to another. The method shown here is to add the option to the list box we are moving to and then remove it from the original list box. In the code above we created two list boxes. One with the ID availableItems and one with the ID selectedItems. To make referencing the availableItems list box easier we created a variable ai. Now we'll do the same thing for the selectedItems list box.
var si=document.getElementById("selectedItems");
Now we get the text and value for the selected item and add them to the selectedItems list box using the process outlined above. To get the text of the option we can use the innerHTML property for the option.
var opt = ai.options[ai.selectedIndex]; si.options[si.options.length] = new Option(opt.innerHTML;opt.value); ai.options[ai.selectedIndex] = null;
The above code works fine if only a single option is selected. If multiple options are selected though, this will not work. Instead we need to determine which options are selected and move them individually. To do this we loop through all of the options and see if they are selected.
function addItems() {
var ai = document.getElementById("availableItems");
var si = document.getElementById("selectedItems");
for (i=0;i<ai.options.length;i++) {
if (ai.options[i].selected) {
var opt = ai.options[i];
si.options[si.options.length] = new Option(opt.innerHTML, opt.value);
ai.options[i] = null;
i = i - 1;
}
}
}
Moving all options from one list box to another
Now lets say we wanted to move all the options from available itms to selected items. It's basically the same thing as above, but we don't need to check to see if the options are selected or not. Also, we use si.options[0] for each option in the loop because as we remove each option the remaining options are re-indexed, so the first remaining option is always ai.options[0].
function addAll() {
var ai = document.getElementById("availableItems");
var si = document.getElementById("selectedItems");
for (i=0;i<ai.options.length;i++) {
var opt = ai.options[i];
si.options[si.options.length] = new Option(opt.innerHTML, opt.value);
}
ai.options.length = 0;
}
Moving an option up or down in a list box
Putting all of this together will allow us to move options from one list box to another one at a time, several selected options, or all options at once. Another feature commonly seen in a list box is the ability to move options up or down in the list. We do this in a manner very similar to adding a new option to a list box.
Let's assume we are moving an option up in the list. The first thing we do is set variables for the value and text of the selected option. We then set the value and text of the selected option index to be the same as those for the option index before the selected index. At this point the selected value is not in the list at all and the preceding option is listed twice. Now we set the text and value of the preceding index from the variables we from the selected option and the two options have traded places. To move down instead of up we simply use the option index after the selected option rather than the one before the selected option. The only thing we have to check for is that we are not at the beginning or the end of the list before we try moving up or down respectively.
function moveUp() {
var si = document.getElementById("selectedItems");
var sel = si.selectedIndex;
if (sel > 0) {
var optHTML = si.options[sel].innerHTML;
var optVal = si.options[sel].value;
var opt1HTML = si.options[sel-1].innerHTML;
var opt1Val = si.options[sel-1].value;
si.options[sel] = new Option(opt1HTML,opt1Val);
si.options[sel-1] = new Option(optHTML,optVal);
si.options.selectedIndex = sel -1;
}
}
function moveDown() {
var si = document.getElementById("selectedItems");
var sel = si.selectedIndex;
if (sel < si.options.length -1) {
var optHTML = si.options[sel].innerHTML;
var optVal = si.options[sel].value;
var opt1HTML = si.options[sel+1].innerHTML;
var opt1Val = si.options[sel+1].value;
si.options[sel] = new Option(opt1HTML,opt1Val);
si.options[sel+1] = new Option(optHTML,optVal);
si.options.selectedIndex = sel +1;
}
}
Sorting the options in a list box
When working with dual list boxes, as the user adds and removes options, the options in the available items box may become out of order. Let's say for example that the user adds the second option from the available list box to the selected list box, and then changes their mind and removes it. Instead of being the second item in the available items list box it is now the last item. This can be confusing for the user. Although not a common feature, this can be solved by sorting the available items list box whenever items are added to it.
We sort the list box by taking all of the options from the list box and adding them to a Javascript array. We can then use a fairly simple Javascript sort command to sort them and then put the values into the list box.
function sortAvailable() {
var ai = document.getElementById("availableItems");
var tmp = "";
// first we create an string from all of the text and
// values of the list box. In this example I use the
// tilde (~) symbol to seperate the text and value and
// use a comma to seperate the options from each other.
for (i=0;i<ai.options.length;i++) {
if (tmp > "") tmp +=",";
tmp += ai.options[i].innerHTML + "~" + ai.options[i].value;
}
// now we split the string into an array using the Javascript
// split function.
var atmp = tmp.split(",")
// sort the array
atmp = atmp.sort();
// Clear the list box
ai.options.length = 0
// Add the sorted options to the list box.
for (i=0;i
Accessing the selected items
The last thing to look at is how do we use the data added to the selectedItems list box. Since a list box will only send the selected items to the page that the form is submitted to, we must select all of the options in the selected items list box prior to submitting the form. We do this by simply looping through all of the options in the selectedItems listbox and marking each one as selected. This function would normally be called by using the onSubmit fuction of the form, or using a standard button rather than a submit button to submit the form.
function frmSubmit() {
var si = document.getElementById("selectedItems");
for (i=0;i<si.options.length;i++) {
si.options[i].selected = true;
}
document.form1.submit();
}