Wednesday, October 04, 2006

Move options across select lists

Perhaps you've seen controls like what is shown to the right where you have some list of items in one selection list and you can move them in and out of another by pressing the '<' and '>' buttons and you want to know how to do it.

Here's one way. First, define your select lists and buttons similarly to that shown below. In my case, I fill in the select options with AJAX, so I have no options defined in the HTML, but if you generated the HTML on the server, then you'll have options in the HTML as well.

<select id="available" size="10" multiple="multiple"></select>
<input type="button" value=">"
onclick="moveOptionsAcross($('available'), $('selected'))" />></input>
<input type="button" value="<"
onclick="moveOptionsAcross($('selected'), $('available'))" /><</input>
<select id="selected" size="10" multiple="multiple"></select>

Now include the following JavaScript code:

// moveOptionsAcross
// Move selected options from one select list to another
function moveOptionsAcross(fromSelectList, toSelectList) {
var selectOptions = fromSelectList.getElementsByTagName('option');
for (var i = 0; i < selectOptions.length; i++) {
var opt = selectOptions[i];
if (opt.selected) {

// originally, this loop decremented from length to 0 so that you
// wouldn't have to worry about adjusting the index. However, then
// moving multiple options resulted in the order being reversed from when
// was in the original selection list which can be confusing to the user.
// So now, the index is adjusted to make sure we don't skip an option.

You should now be able to select options in one list and press the appropriate button to move them to the other list.


Anonymous said...

Man, this is great! Thanks for posting this information.

I've been having some trouble moving options around inside of selects as well as moving between selects. I used the examples from both of your blogs and they work flawlessly, even in IE7.


Webbaysys said...

I used the same code but its not working.

Please help me out in fixing this.


Anonymous said...

I had to change the code up a bit to get it to work. The $ sign thing was not working.

Anonymous said...

It is very interesting for me to read the post. Thanks for it. I like such topics and everything that is connected to them. I definitely want to read more soon.

Anonymous said...

I wish not approve on it. I regard as nice post. Particularly the appellation attracted me to study the whole story.

Anonymous said...

Amiable brief and this post helped me alot in my college assignement. Say thank you you on your information.