Moving options between select boxes

Just a quick post. I needed to be able to display a multi-select box showing all the options available to a user, and allow the user to select one or several, and ‘move’ them to their list of chosen options. Then, when the form is submitted, make sure only the items in the chosen list of options is submitted.

Fairly easy right? It was, but took long enough that I wanted to share and tag appropriately, in case people come looking for it. :)

Image of what I wanted:
Multiselect image

Link to my working JSFiddle.

HTML:

<form action="javascript:void(0);"> 
   <select multiple="multiple" name="all_options" class="all_options">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
        <option value="5">Five</option>
    </select>
    <button class="go_in">in</button>
    <button class="go_out">out</button>
    <select multiple="multiple" name="chosen_options" class="chosen_options">
        <option value="7">Seven</option>
    </select>
    <br/><input type="submit" value="submit">
</form>

Javascript:

$('.go_in').click(function() {
    return !$('.all_options option:selected').remove().appendTo('.chosen_options');
});
$('.go_out').click(function() {
   return !$('.chosen_options option:selected').remove().appendTo('.all_options'); 
});
 
$('form').submit(function() {
    $('.all_options option').prop('selected','');
    $('.chosen_options option').prop('selected','selected');
    alert($(this).serialize());
});

2 thoughts on “Moving options between select boxes

  1. By wild coincidence this is just what I was going to ask you about if you recall that database project I’m working on in LibreOffice. So thanks! When I have a moment I’ll see if I can take some steps toward implementing this. One suggestion, I think the usability would improve with arrow buttons rather than in/out.

    • That is awesome that it is helpful to you! I agree about implementing arrows. Honestly, I was lazy and didn’t want to take the extra 3 keystrokes to implement the html codes for greater than and less then. :/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>