Create Add & Remove Select Lists Using jQuery

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 &raquo;</a>
    <a href="JavaScript:void(0);" id="btn-remove">&laquo; 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.

Check out the jquery add & remove select list demo.

One Response to “Create Add & Remove Select Lists Using jQuery”

Leave a Reply