Connected Multiselect Boxes

The following code snippet is a quick and easy way to selectively create a list from options in a secondary multiselect box. As it's multiselect you'll be able to move more than one option to the other list at the same time. Note this example doesn't include sorting the order, for this you might want to look at using something like JQuery sortables. 

The following code will consist of two multiselects and an add and remove button to switch between the two lists. If both lists are equally important (e.g. sorting teams) you could just change these to arrows.

The HTML

First create the options multiselect:

<select id="options" multiple="multiple">
<option value="1">Monkey</option>
<option value="2">Ostrich</option>
<option value="3">Lion</option>
<option value="4">Dolphin</option>
</select>

Next add some buttons to move the options between the two lists, onclick they each utilise the moveOption function which we'll add shortly. For simpliciy the onclick action has been added inline, though you could move this inside your javascript file if you wanted to.

<input onclick="moveOption('options','selected')" type="button" value="add">

<input onclick="moveOption('selected','options')" type="button" value="remove">

...and now add the other multiselect box (with a bit of styling you could line these up side by side).

<select id="selected" multiple="multiple"></select>

The Javascript

This example is built in Jquery, though could easily be adapted. So to implement this example include Jquery with this script in the head of your document:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

...and lastly add the javascript to move the options between boxes:

<script type="text/javascript">
function moveOption(from, to)
{
    $("#" + from + " :selected").each(function ()
    {
          $('#' + to).append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
          $('#' + from + ' option[value="' + $(this).val() + '"]').remove();
    });
}
</script>

 

Example

In the example below I've wrapped a division around the select boxes and buttons and floated each division left, this is an easy way to line everything up.

 
 
Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.