Thursday, October 05, 2006

MANIPULATING LISTBOXES IN JAVASCRIPT


Ever occured the problem of moving elements from one ListBox to another? It can be done easily on server side, but what if you could get rid of those annoying postbacks? Here's a tip:

An asp ListBox renders as follows:

<select ...>
<option value="aaaaa">aaaaa</option>
<option value="bbbb">bbbb</option>
<option value="ccc">ccc</option>
...
</select>

The following code snippets might be useful in such case:

1. you need to have an array with all elements of the first ListBox
var myListbox = document.getElementById(lb1Id); // lb1Id is the ClientId of the control
var myListboxOptions = myListbox.getElementsByTagName("option");

2. need a clone of the original ListBox and a clone of all options
var cloneOfMyListbox = myListbox.cloneNode(true);
var cloneOfMyListboxOptions = cloneOfMyListbox.getElementsByTagName("option");

3. you need the other ListBox
var otherListbox = document.getElementById(lb2Id); //lb2Id is the ClientId of the second control

4. and the mechanisms for moving certain elements from the first ListBox to the second one
otherListbox.appendChild(cloneOfMyListboxOptions[index].cloneNode(true)); // add element to the second control
myListbox.remove(index); // remove the element on the specific index from the first control

No comments: