JQuery makes it very easy to select specific elements and their attributes in your web page HTML.
In the following tutorial I will show you how to use just a few lines of jQuery to create an add/remove select list for your website form.
The Form HTML
<form>
<fieldset>
<select name="selectfrom" id="select-from" multiple size="5">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
<a href="JavaScript:void(0);" id="btn-add">Add »</a>
<a href="JavaScript:void(0);" id="btn-remove">« Remove</a>
<select name="selectto" id="select-to" multiple size="5">
<option value="5">Item 5</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
</select>
</fieldset>
</form>
So here we have just 2 select lists with sample data – the top one listing the items “from”. There are also 2 anchor tags, which provide the “add” and “remove” links.
The jQuery Code
$(document).ready(function() {
$('#btn-add').click(function(){
$('#select-from option:selected').each( function() {
$('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
$('#btn-remove').click(function(){
$('#select-to option:selected').each( function() {
$('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
});
Basically what we do here is that when either of the “add” or “remove” links are clicked jQuery will get the values for all of the relevant options that are selected, recreate each option item HTML, insert it into the opposite select list and finally remove these items from the original list.


















Hey thanks a lot!, you helped me to find the answer to my problem. I was looking for some solution that would remove a list item which had no id or something that identify it
Thank you for your clear explanation and nice code.
your welcome
How do you pull the new values for sending via Jquery ajax, when call via value attribute the value is returned empty.
To get the value of the select options use:
$('#select-to option').each(function(){ $(this).val(); });Nice snippet,
Have you thought of adding a counter to have max list count? So the user could add a maximum of eight options.
This is something I am working on for adding tags to an article, so the user can choose from a set of pre-defined tags.
If you have a solution let me know.
You can use the length property to count the number of options in the select list – e.g
$('#select-from option:selected').each( function() { $('#select-to').append(""+$(this).text()+""); $(this).remove(); var checkLength = $('#select-to option').length; alert(checkLength); });See Demo
[...] Contacts « Create Add & Remove Select Lists Using jQuery [...]