jMar"s Blog DevSmash Developer Portal

Friday, February 8, 2008

Easy Multi Select Transfer with jQuery

I'm sure that at some point or another you've encountered a form widget like the one below, allowing options to be traded from one multi select to another.

add >>

I recently encountered a tutorial over at Quirks Mode on creating such a widget. While not a bad script, when all was said and done it was coming up on 40 lines of JS. I suppose that's not horrible, but we're talking about some simple functionality.

This struck me as a perfect example to demonstrate the simple and compact nature of jQuery coding. The widget operating above is running off of the following code:

$().ready(function() {
 $('#add').click(function() {
  return !$('#select1 option:selected').remove().appendTo('#select2');
 });
 $('#remove').click(function() {
  return !$('#select2 option:selected').remove().appendTo('#select1');
 });
});

That's it... 8 lines.

If you'd like to try it out, here's a working test page:

<html>
<head>
 <script src="js/jquery.js" type="text/javascript"></script>
 <script type="text/javascript">
  $().ready(function() {
   $('#add').click(function() {
    return !$('#select1 option:selected').remove().appendTo('#select2');
   });
   $('#remove').click(function() {
    return !$('#select2 option:selected').remove().appendTo('#select1');
   });
  });
 </script>
 
 <style type="text/css">
  a {
   display: block;
   border: 1px solid #aaa;
   text-decoration: none;
   background-color: #fafafa;
   color: #123456;
   margin: 2px;
   clear:both;
  }
  div {
   float:left;
   text-align: center;
   margin: 10px;
  }
  select {
   width: 100px;
   height: 80px;
  }
 </style>
 
</head>

<body>
 <div>
  <select multiple id="select1">
   <option value="1">Option 1</option>
   <option value="2">Option 2</option>
   <option value="3">Option 3</option>
   <option value="4">Option 4</option>
  </select>
  <a href="#" id="add">add &gt;&gt;</a>
 </div>
 <div>
  <select multiple id="select2"></select>
  <a href="#" id="remove">&lt;&lt; remove</a>
 </div>
</body>
</html>

As was mentioned in the comments below, the following (slightly modified) code can be used to automatically select all options in the second select box before submitting (thanks Charlie!).

$('form').submit(function() {
 $('#select2 option').each(function(i) {
  $(this).attr("selected", "selected");
 });
});

Just make sure you include that snippet inside the $().ready() method.

Update! (2/28/2008)

To prevent the page from scrolling to the top whenever a user clicks a button (in some browsers), I added return false; to the click event handlers.

(3/07/2008)

I included Charlie's suggestion from the comments into the main article. Thanks again Charlie! I also updated the the click event handlers to return false on the same line. Now it's only 8 lines!

(6/24/2008)

David Walsh has done an excellent port of this script for the Mootools library. You'll notice that the libraries allow for very similar syntax and nearly identical flow of logic. Check it out!



167 comments:

Charlie said...

If you are using a form and want to add a submit button that will select all the entries in the select field with the id "select2", before submitting the form, just add this function (like the original javascript example):

$("form").submit(function() { $('#select2').each(function(){
$('#select2 option').attr("selected","selected");
});

(excuse the formatting)

delgo said...

When I try to swith the Items when clicking on them, the one direction works fine (left to right), the other doesn't (FF2).
In IE6 ist doesn't work at all.

$("#pn_skills1 option").click(function () {
$("#pn_skills1 option:selected").remove().appendTo("#pn_skills");
});
$("#pn_skills option").click(function () {
$("#pn_skills option:selected").remove().appendTo("#pn_skills1");
});

cu
rigo

Jeremy Martin said...

@delgo

I just deleted my post from a few minutes ago because I got a solution that will work in IE6 too. Here it is:

$().ready(function() {
$("#pn_skills").change(function (e) {
$("#pn_skills option:selected").remove().appendTo("#pn_skills1");
});

$("#pn_skills1").change(function (e) {
$("#pn_skills1 option:selected").remove().appendTo("#pn_skills");
});
});

IE6 won't automatically update the size of the select box, so you'll need to do that through styling (if you haven't already).

ap said...

Ok, after pulling quite a few small bundles of hair from my weary skull I finally discovered why values weren't transmitted upon hitting the submit button. They have to be selected by the user in the browser, just adding 'selected' to the option tag won't cut it. Doh! As always the solution to this is maddening easy, I solved my woes with this code:

$('input[@type=submit]').click(function() {
$('#select2 *').attr('selected','selected');
});

hth,

ap

Ps. thanks a bunch for your jquery code, you really should make it into a nice manageable jquery plugin... Great addition to my toolbox :D

David said...

Hello Jeremy,

Could you please contact me about this article? I'd like to talk to you about promoting this article to a larger audience.

Thank you!

David

Jeremy Martin said...

@David
I would love to follow you up on this, but I don't know who you are or how to contact you :)

David said...

Hello again Jeremy,

Please hit me from your personal email -- mine is david@davidwalsh.name. Please send a quick email there and I'll explain what I'd like to do.

Thank you!

David

Nate said...

Here is basically the same thing without jquery (or any other library), and still 11 lines of code.

function $(id) { return document.getElementById(id); }
function moveFromTo(fromId, toId) {
var optionElems = $(fromId).getElementsByTagName("option");
var i;
for(i = 0; i < optionElems.length; i++) {
if(optionElems[i].selected) {
$(toId).appendChild(optionElems[i]);
i--;
}
}
}

It doesn't have the event handlers, since I was doing that inline.

Jeremy Martin said...

@Nate
Not to take away from your script, but if we're handling the events inline, then jQuery let's me do this function in one line:

function moveFromTo(fromId, toId) { return !$('#'+fromId).children('option:selected').remove().appendTo($('#'+toId)); }

:p

Nate said...

Yeah... I know how great jquery is.
I had to write that before I was allowed to use a 3rd party library, and I was posting the code more for comparison to the 40 line non-jquery function you were talking about.

Jeremy Martin said...

Ya, I have to agree your version is definitely more concise than the one at Quirks Mode. Libraries can definitely be a life saver, but I would never use them unless my site needed a lot of dynamic content. Otherwise the overhead isn't worth it.

Nate said...

...just for the hell of it, here it is in 6:
function moveFromTo(fromId, toId) {
var optionElems = document.getElementById(fromId).getElementsByTagName("option");
for(var i = 0; i < optionElems.length; i++) {
optionElems[i].selected ? document.getElementById(toId).appendChild(optionElems[i--]) : continue;
}
}

I could probably squeeze in an event handler in without going over 11, but I don't think I could get anything close to the jquery $ selector stuff in there.

Jeremy Martin said...

Not too shabby. The one recommendation I would make is to have the function return false. That way if the event trigger is an anchor, the page won't skip to the top every it's clicked.

That's why in my one line version I returned !$(...).[do stuff].
Since the line always returns a jQuery object, returning !$() will always return false.

Scott said...

I have been using a similar piece of code on my football website. I am looking to add to it further if someone here can help.

I am using it for adding players to a match and want to have something to limit the amount that can be added to the second select box. Also have a popup it they have not selected enough.

Thanks Scott

Jeremy Martin said...

@Scott
I have a script that should work for you, but it is longer than I'd rather leave in the comments. If you can provide me with an email address I could send it to you though.

Scott said...
This comment has been removed by a blog administrator.
Jeremy Martin said...

@Scott
I sent you the script, and I also deleted your comment with your email address (to save you from crawlers...). Hope it works for you.

Horacio said...

Hm, i've a select box, that when it changes, changes the current window location.

onChange="eval('location=\''+this.options[this.selectedIndex].value+'\'');"

So, if i want to add 2 buttons, one for go forward the actual selection, and other to go backward, what should be the solution?

Andy D, Hajime said...

one the item i want to add is on the right side, how do i save the right side value to database or anywhere???

Jeremy Martin said...

@Andy
Take a look at the last code block in the article. It selects all of the options in the right multi select when the submit button is clicked. That causes all of the values in that select to be posted.

Anonymous said...

you may want to add name="select2[]"
to handle multiple selections in the$_ POST

Anonymous said...

Also, how can you add / remove all entries?
Thanks, in advance.
-Chado

Alex said...

Hi, this is really cool.

Would it be possible to have more than one set of these select boxes yet only one relevant javascript codeblock in the header?

What I mean to ask is: does the "select1" and "select2" names need to be in the javascript codeblock? or could it be smart enough to know which set of select's it should be working on?

Jeremy Martin said...

@Alex
It would definitely be possible - but the code would need to be re-factored using a $(xxx).each(...) loop. For example, if you assigned all of the left and right side selects with classes of "left" and "right", respectively, then it could be coded something like this:

$('.left').each(function() {
$(this).click(....);
$(this).next('.right').click(...);
}

Anonymous said...

can we get the code for an add all and remove all button?

Thanks
Chad

Alex said...

Thanks Jeremy, I almost understand what you're getting at (newbie with javascript/jquery).

This is a good start, any more tips would be greatly appreciated.

I'm trying to use this option transfer with multiple sets of data and trying to figure out a way where my php code can generate each select-pair with unique id's which all work with your cool javascript code.

thanks again

Alexey Shockov said...

Hello, Jeremy!

Your script is cool, but I think, that we must deselect moved items... Something like this:

$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2').removeAttr("selected");
});
$('#remove').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1').removeAttr("selected");
});
});

I add removeAttr method call... It's, IMHO, more usable ;)

Jeremy Martin said...

@Alexey -
Good suggestion. I've received so many good tips on this board it seems the original script is in need of an overhaul. I admit that the original purpose was simply to demonstrate the simplicity of using jQuery, but it definitely can't hurt to improve its usability while we're at it... thanks for the tip!

Shannon Ryan said...

Thanks for the code.

It helped me quite a bit.

Anonymous said...

Thanks for the code it was very helpfull.
But could you tell me how to send couple values to database from this form?

yitzc said...

Using the Livequery plugin, I was able to implement double clicking an option to move it from one select to the other:

$("#select1 option").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select2');
});
$("#select2 option").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select1');
});

Jeremy Martin said...

@Anonymous
Unfortunately I threw this example together too quickly with an emphasis on demonstration, rather than usability. To actually post the selected values back to the server (novel idea), you need to:
1. Change "select2" to "select2[]" (in both the script and the markup).
2. Make sure you implement the last code block in the example (that actually selects all the elements in select[] prior to posting).
Let me know if you have any further questions!

@yitzc
That's an excellent addition. I'm really going to have to completely redo this post with an emphasis on usability and progressive enhancement (this current version is dead in the water without JS enabled). This is also an excellent example of where Livequery can simplify your code. You could obviously achieve the dblClick transfer w/out livequery, but then you'd have to inspect each option's parent select each time. Great work!

letsrock said...

I'm sorry but I just don't understand what is required to get this amazing widget to post.

Where exactly does the last part of the code go? Could you please respost the code including all elements to make it functionally able to post selected values from select box 2 on submit?

Thanks very much.

murki said...

@Nate and #jeremy_martin

Have you noticed that this produces a strange behavior (bug) in IE/? Shrinking the select inputs. Somebody else have noted that here: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3599221&SiteID=1

Do you know anything on this subject? It's happening to me and it's very annoying. Thanks!

Jeremy Martin said...

@letsrock
The last part of the code could be included nearly anywhere. I would suggest putting it in the same script block below the rest of the code. Did you try following all the suggestions in the comment thread?

@murki
I had not noticed this IE7 bug before. After reading the article you referenced it would appear that your frustration is shared. Unfortunately I don't have any workaround at this time, and I'm not sure when I'll be able to look into it further. Wish I had better news for you!

blackthorne said...

I read many suggestions and tips. Has the code from the original been updated or do I have to go threw all comments until reaching an "Easy" Multi Select Transfer with jQuery?

Thanks

Rob said...

Hi,

Thanks for your script but I'm having trouble with it. Any chance anyone could tell me what's wrong with this?

It won't let me input the code so I've had to link to it here (hope this is appropriate):

http://76.163.22.145/multiselectjquery.txt

It's formatting ok and the php is filling in the selects but it's not passing from contbox1 over to contbox2.

Is there something I'm missing here?? It's driving me nuts!

Thanks.

Rob

Rob said...

I got it going, because I am planning to have 4 multi select boxes on the page, I was wrapping all of the function in one <script> tag when I should have been wrapping them individually..

Great script, thanks!

Rob.

KeithHopkin said...

Here is an example of making this function more modular.

your buttons should look something like this:


input type="button" value="Add >>" id="regionId_add" onclick="addMultiSelect('idOfFirstSelect');"/
input type="button" value="<< Remove" id="regionId_remove" onclick="removeMultiSelect('idOfSecondSelect');"/

inside of a javascript tag somewhere on your page or an included js file:

function addMultiSelect(id){
$('#'+ id + ' option:selected').remove().appendTo('#' + id + '_list');
}
function removeMultiSelect(id){
$('#'+ id + '_list option:selected').remove().appendTo('#' + id);
}

terminals-blocks said...

When I try to swith the Items when clicking on them

ndev said...

Thanks for your tutorial.

I tryed to select from many lists.

I'm sure it could be done writing less code. I would welcome your help

<html>
<head>
<!-- <script src="js/jquery.pack.js" type="text/javascript"></script> -->
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>

<script type="text/javascript">
$().ready(function() {
$('#add1').click(function() {
return !$('#select1 option:selected').clone(true).appendTo('#selectALL');
});
$('#add2').click(function() {
return !$('#select2 option:selected').clone(true).appendTo('#selectALL');
});
$('#add3').click(function() {
return !$('#select3 option:selected').clone(true).appendTo('#selectALL');
});

$('#remove').click(function() {
return $('#selectALL option:selected').remove();
});
});
</script>

<style type="text/css">
a {
display: block;
border: 1px solid #aaa;
text-decoration: none;
background-color: #fafafa;
color: #123456;
margin: 2px;
clear:both;
}
div {
float:left;
text-align: center;
margin: 10px;
}

select {
width: 120px;
height: 130px;
}

#target {
clear:left;
}

#target select {
height: 200px;
width: 250px;
}
</style>

</head>

<body>
<div> <p>List A</p>
<select multiple id="select1">
<option value="a.1">A. Option 1</option>
<option value="a.2">A. Option 2</option>
<option value="a.3">A. Option 3</option>
<option value="a.4">A. Option 4</option>
<option value="a.5">A. Option 5</option>
<option value="a.6">A. Option 6</option>
<option value="a.7">A. Option 7</option>
<option value="a.8">A. Option 8</option>
</select>
<a href="#" id="add1">add</a>
</div>

<div> <p>List B</p>
<select multiple id="select2">
<option value="b.1">B. Option 1</option>
<option value="b.2">B. Option 2</option>
<option value="b.3">B. Option 3</option>
<option value="b.4">B. Option 4</option>
</select>
<a href="#" id="add2">add</a>
</div>

<div> <p>List C</p>
<select multiple id="select3">
<option value="c.1">C. Option 1</option>
<option value="c.2">C. Option 2</option>
<option value="c.3">C. Option 3</option>
<option value="c.4">C. Option 4</option>
</select>
<a href="#" id="add3">add</a>
</div>

<div id='target'> <p>Selected options </p>
<a href="#" id="remove">remove</a>
<select multiple id="selectALL"></select>

</div>
</body>
</html>

ndev

Mychael said...

This is great, but I have one question. I have an array that I would like to populate the second box with (Also remove those options from the first one). How would I go about doing this. It's a PHP array ($key => $value).

Anonymous said...

Mychael - to pre-populate the second select box it's as simple as adding the option tags with their values inside the second select box tags. The script already supports the adding and removing of the values reguardless of the pre-population of either select box.

tekomp said...

Is it possible to preserve the order of the options?

Serg said...

amazing! Thx!

Serg.

Pixie said...

this is very cool, I hope I can find a reason to use this!

TheUnknown said...

Did anyone ever find out if you can retain the original sort order of the select1 column? It's the only thing missing from this great piece of code. Thnx!

TheUnknown said...

Also - one other question. After a submit - if I returned to the same page how would I re-populate the select boxes with the users choices? Meaning the selected options are removed from Column1 and they are appended to Column2. Much appreciated.

Albert said...

I am facing a problem.
Please help me

When i tried to move a option from on multiselect box to other. The value of that option is not set in the copied select box
what to do???


Thanks in advance

Lokesh said...

Great Post.
Helped a lot.

Thanks Man

Ajans said...

Thanks you too much, this is wonderful !

vank said...

Thanks alot!!

almost build a new plugin just to handle similar problem...
now i can sleep peacefully, thx!

Jake Toolson said...

Thanks for the write-up. I'm currently implementing it on my website.

Has there been anyone who's been able to figure out a way to "sort" the 2nd list?

Also, I use options grouping...

I am only able to move [options] to the right column, but how can I make sure the options are appended to the correct [optgroup] ?

Thanks

schmappel said...
This comment has been removed by the author.
schmappel said...

Here's another approach to the same problem.

Oskar said...

@yitzc: doubleclick behavior is simple enough to implement without livequery:

function add() {
return !$('#select1 option:selected').remove().appendTo('#select2');
}
function remove() {
return !$('#select2 option:selected').remove().appendTo('#select1');
}
$().ready(function() {
$('#add').click(add);
$('#select1').dblclick(add);
$('#remove').click(remove);
$('#select2').dblclick(remove);
});

oyun oyna said...

thanks for tutorial. its usefull

Naveen Nayak said...

Thank you very much for the nice code :)

dış cephe said...

Its great.thanks a lot.

Anonymous said...

How does this sound?

transfer: function(fromId, toId) {
return !$('#'+fromId).children('option:selected').remove().appendTo($('#'+toId));
}

maç oyunları said...

This is a good start, any more tips would be greatly appreciated.

Manuel J. Silva said...

Hi there, first let me thank you all for the code snippets really helpful to accomplish what I have in hands.

As some users already have asked I also needed a function to Add All and another to Remove All, being a jquery newbie I've accomplished it by tying what makes more sense, and finally it worked

Here is the code:
$("#addAll").click(function() {
$("#select1").each(function(){
return !$('#select1 option').remove().appendTo('#select2').removeAttr("selected");
});
}) ;

$("#removeAll").click(function() {
$("#select2").each(function(){
return !$('#select2 option').remove().appendTo('#select1').removeAttr("selected");
});
}) ;


(sorry the formatting)

web tasarımı said...

When I try to swith the Items when clicking on them, the one direction works fine (left to right), the other doesn't (FF2).
In IE6 ist doesn't work at all.

online game guide said...

Ok, after pulling quite a few small bundles of hair from my weary skull I finally discovered why values weren't transmitted upon hitting the submit button.

savaş oyunları said...

Thank you very much for the nice article..

barbie oyunu said...

I have gotten many comments from people telling me that it is a bad idea to give away my music under creative commons.

yarış oyunları said...

I just deleted my post from a few minutes ago because I got a solution that will work in IE6 too.

ev oyunları said...

Thanks for your tutorial.
I tryed to select from many lists.

kız oyunu said...

It's the only thing missing from this great piece of code. Thanks!

Karl said...

This is working great for me, but I'm wondering if there's anyway to limit the number of selected options to say 5?

Karl said...

This seems to be working for me to limit the amount of selections, but this is the first time I've done any experimentation with jQuery. Is this a good way or is there a better way to accomplish limiting the number of selections?

Thanks.

$('#add').click(function() {
selectlength = $('#category-select')[0].length;
addlength = $('#category-list option:selected').length;
if((addlength + selectlength) <= 5)
return !$('#category-list option:selected').remove().appendTo('#category-select');
});

Karl said...

This seems to be working for me to limit the amount of selections, but this is the first time I've done any experimentation with jQuery. Is this a good way or is there a better way to accomplish limiting the number of selections?

Thanks.

$('#add').click(function() {
selectlength = $('#category-select')[0].length;
addlength = $('#category-list option:selected').length;
if((addlength + selectlength) <= 5)
return !$('#category-list option:selected').remove().appendTo('#category-select');
});

kaigou said...

Hey. I've been looking for a good version of the multi-select box, since my app has several fields with options in the hundreds (yeahyeahIknow). Kinda annoying when what should be helpful js seems to take almost as many lines as the box's own output. But! Finally! Someone who did it in less than eighty lines! I mean, really. Your code totally ftw.

As for posting to the db, I read the suggestions, but discovered something I thought you'd like to know. If, in the second box's select info, you add name="select2[]", then you don't even need that js addendum. A standard $_POST wants name, anyway, which I think is why the proc_page was spitting out id="select2[]" but chomped name="select2[]" with no complaint.

The other thing I discovered is that it's true about jquery, that it won't always behave in the /head/ section but does just fine if inside the body. And being a lazy coder, that meant I could squish it all into a PHP function. Saves me time/headaches while I'm dealing with design layer around oodles of code.

function jmar($num, $table, $args = '' ) {
extract($args);
if (!$css1) { $css1="f2"; }
if (!$css2) { $css2="fx medp"; }
if ($prx) { $table == $prx.'_'.$table; }
echo '<script type="text/javascript">'; ?>
$().ready(function() {
$('#add').click(function() {
return !$('#select<?php echo ($num-1); ?> option:selected').remove().appendTo('#select<?php echo $num; ?>');
});
$('#remove').click(function() {
return !$('#select<?php echo $num; ?> option:selected').remove().appendTo('#select<?php echo ($num-1); ?>');
});
}); <?php
echo '</script><div class="'.$css1.'"><select multiple id="select'.($num-1).'" class="'.$css2.'">';
$result = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_array($result)) { echo '<option value="'.$row['id'].'">'.$row['description'].'</option>'; }
echo '</select><br><div class="buttons"><a href="#" id="add">add <img src="img/icons/arrow_right.png"></a></div></div>';
echo '<div class="'.$css1.'"><select multiple id="select'.$num.'" class="'.$css2.'" name="select'.$num.'[]"></select><br>';
echo '<div class="buttons"><a href="#" id="remove"><img src="img/icons/arrow_left.png"> remove</a></div></div>';
}
?>


There are two css classes used, one for the overall div & the other for the individual boxes, so I set defaults for those. The 'selectN' value is either itself or (n-1), so as long as I step up by even numbers, the function won't overlap. Other than remembering which N is which when prepping for db insert, it's now total piece of cake. Good thing, too, since I'll be reusing this function too many times to count in this app.

Thanks again! Your post was a HUGE help! Like, HOURS SAVED kind of help!

web tasarım said...

klima servisi olarak çalışırken öncelikle servisin klima konusuna ne kadar hakim olduğu bilinmelidir.

Mehmet Emre said...

I've been searching for something like this for a longsiemens servisi olarak çalışırken öncelikle servisin ariston ürünlerde uzman olup olmadığına bakılmalıdır.
ariston servisi kullanımı ariston ürünlerinin servis imkanını arttırmıştır.
general electric sevisi seçerken dikkat ediyor muyuz ?general electric servis ve servislerini kullnanalım.

Hosting said...

Ok, after pulling quite a few small bundles of hair from my weary skull I finally discovered why values weren't transmitted upon hitting the submit button.

Anonymous said...

Thanks. Simple and great solution

Pratik Khadloya said...

By default IE does not submit the disabled values from the select box.
If one wants to submit the disabled values also, need to do the following tweak:
$jQuery('form').submit(function(){
$jQuery('#select1 option').each(function(i){
$jQuery(this).attr("disabled", "");
$jQuery(this).attr("selected", "selected");
});
$jQuery('#select2 option').each(function(i){
$jQuery(this).attr("disabled", "");
$jQuery(this).attr("selected", "selected");
});
});

ugonaloveme said...

Hi All,
I am using cakePhp, I am unable to post the data...
when i prints : $this->data,
It shows an empty array for secondselectbox.
????

bobk said...

Thank you from the Netherlands for this sample. I have programmed functions like this manually. This is much simpler to maintain and gives a better user experience!

Web Tasarımı said...

good post...bu multiple select not active?

ADSELL said...

Hi this message is very beautiful and useful information to your offers. Thank you for information.

Anonymous said...

very good artichle
thank you

film izle said...

$("#pn_skills option").click(function () {
$("#pn_skills option:selected").remove().appendTo("#pn_skills1");
});

Samir said...

Nice and so elegant solition! Thank you for sharing! =)

güzel oyunlar said...

I'd like to talk to you about promoting this article to a larger audience.

juegos de bebes said...

This is much simpler to maintain and gives a better user experience!

onlinesitem said...

thank you share

Yemek Tarifleri said...

Thanks have never seen this article before. Regards Steven.

film seyret said...

This is much simpler to maintain and gives a better user experience!

film seyret said...

This is much simpler to maintain and gives a better user experience!

Anonymous said...

if only want a limit number of select transfer, How can I do...pls help...tks

Brian said...

if only want a limit number of select transfer, How can I do...pls help...tks

Marble said...

Gota love sexy code! If anyone is wondering how you can sort or maintain order when adding/removing, I've come up with a solution that works very well, but it's more like 30 lines of code because I place the text of the options in two arrays, combine the arrays, then sort the array, build the new options list and replace the html.

Anonymous said...

I just noticed that the code is broken when using jQuery 1.4+ in IE8. This code fixes IE8 and works in firefox as well:

$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
});

Anonymous said...

Thank you very much for the nice article..

Marcus said...

This solution is fantastic. However, I'm searching a solution for more than 1 select-box incl. double click support.
Anyone can help me with this?

rafael mota said...

to send values to php select2 on another page?

web tasarım said...

Hm, i've a select box, that when it changes, changes the current window location.

onChange="eval('location=\''+this.options[this.selectedIndex].value+'\'');"

So, if i want to add 2 buttons, one for go forward the actual selection, and other to go backward, what should be the solution?

Senamion said...

My jQuery plugin is the final solution: http://www.senamion.com/blog/jmultiselect2side.html

Anonymous said...

I was trying out your code because I am trying to avoid checkboxes, they are so ugly to me but I am having an error pop up and I hope this wasn't posted already and I missed it. But the error says "multiple" must be followed by '=' character. Any thoughts to this? Thanks!

video indir said...

Hi there, first let me thank you all for the code snippets really helpful to accomplish what I have in hands.

As some users already have asked I also needed a function to Add All and another to Remove All, being a jquery newbie I've accomplished it by tying what makes more sense, and finally it worked

Here is the code:
$("#addAll").click(function() {
$("#select1").each(function(){
return !$('#select1 option').remove().appendTo('#select2').removeAttr("selected");
});
}) ;

$("#removeAll").click(function() {
$("#select2").each(function(){
return !$('#select2 option').remove().appendTo('#select1').removeAttr("selected");
});
}) ;

Majid said...

Hi,
thanks for this tutorial,

I am trying to use this code in a jsp file to have two lists :

First populate the lists from the database :

AllRolesMinusAssignedRoles

and

AssignedRoles

when transfering data between the two lists, press save to save data back to the database.

Has somebody did someting similar ?

thanks.

Anonymous said...

Thanks Jmar, this was exactly what I was trying to do.

ucuz web tasarım said...

Hm, i've a select box, that when it changes, changes the current window location.

onChange="eval('location=\''+this.options[this.selectedIndex].value+'\'');"

So, if i want to add 2 buttons, one for go forward the actual selection, and other to go backward, what should be the solution?

Vladimir Kelman said...

A pretty much complete example which is working in all major browsers and support auto-sorting of transferred Options and Optgroups could be found at http://goo.gl/sgPv

Anonymous said...

Hi,

I have 3 multiple selects. In the first Select1(left) I load a group of modules. In the 3rd Select3(right) I load another group of modules. The user can select from the Left and hit an add to remove the item from the Left and append it to the Select2(Middle). The user can do the same with the Right, select items hit a different add where the selections will be appended to the middle and removed from the Right.

This all works fine.

I want to enable the user to remove from the Middle multi-select. I only want one occurence of the remove . If the user selects items that were formally contained in both the Left and Right multi-select I want them to be removed from the Middle and appended to the Left and Right according from where the orignially came from. I have a variable setup to determine where the module selected in the middle originally came from.

Im having problems with the actual append/removal of the ITEM from the middle back to the Left / Right multiple selects. Ive googled and tried various things but its taking too long.

The following script shows only the interaction with the Left and Middle selects. I will use any solutions as a model for the Middle, Right relationship.

Any help would be greatly appreciated


$().ready(function() {
$('#add_mod').click(function() {
return !$('#select1_mod option:selected').remove().appendTo('#select2_mod');
});
$('#remove_mod').click(function() {
var x = "<%= str(modules) %>";
$("#select2_mod option:selected").each(function (i,selected) {
var thismod = $(this).text();
if (x.match(thismod))
// HELP Here I want to append this item (text and value) to Select1
// HELP Plus, remove this item from Select 2
//else after I get a solution for Left/Middle
});
// HELP And then return Select1, Select2, Select3
});
});

Anonymous said...

Here is the answer to my add item problem.


$().ready(function() {
$('#add_mod').click(function() {
return !$('#select1_mod option:selected').remove().appendTo('#select2_mod');
});
$('#remove_mod').click(function() {
var x = "<%= str(modules) %>";
var thisind = 0;
$("#select2_mod option:selected").each(function (index) {
var thismod = $(this).text();
var thisval = $(this).val();
if (x.match(thismod)) {
$(this).remove().appendTo('#select1_mod');}
else {
$(this).remove().appendTo('#select1_ms');}
});
});
$('#add_ms').click(function() {
return !$('#select1_ms option:selected').remove().appendTo('#select2_mod');
});
$('#remove_ms').click(function() {
return !$('#select2_ms option:selected').remove().appendTo('#select1_ms');
});

});

Anonymous said...

Thanx!!! Really useful!!!!

Flavio Oliva said...

http://www.packtpub.com/article/simple-item-selector-using-jquery

Catur said...

thx..
very easy n usefull

Kitsch said...

Many thanks! Your ideas put me in the right direction.

Chinjith Sasidharan said...

Thanks a lot!
You have done a gr8 work. I have simply included the code and changed the id's . It worked.

Thanks again. Simply the BeSt.

Kaos said...

How can I populate select1 from an sql query?

Samuel said...

Thanks for scripting it is very use to easy.................... again many thanksssssss

Sunny said...

I am trying to use your scripts on one of my web sites and I just can't seem to get it to work on IE or Safari browsers.

Here's the code:

$(document).ready(function() {
/*$('#add').click(function() {
return $('#select1 option:selected').remove().appendTo('#select2');
});
$('#remove').click(function() {
return $('#select2 option:selected').remove().appendTo('#select1');
});*/
$('#select1 option').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$('#select2 option').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
})
});

The contents from Select 1 are not moving to Select2.

Can you please help.

Thanks

Sunny said...

Nevermind - I got it working :-)

Sunny.

Sunny said...

This is an awesome script - saved me a lot of time.

I am trying to implement a double-click event using livequery ( as suggested by somebody on this forum )

I downloaded livequery and tried the following, but to no avail.

$("#select1 option").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select2');
});
$("#select2 option").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select1');
});

I also tried:

$("#select1 option:selected").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select2');
});
$("#select2 option:selected").livequery('dblclick',function() {
return !$(this).remove().appendTo('#select1');
});

It simply doesn't work. Any suggestions/help would be great.

Thanks

Sunny said...

Adding to my earlier post regarding double-click event.

The following code works great in Safari but fails in IE 6:


$("#select1 option").livequery('dblclick',function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$("#select2 option").livequery('dblclick',function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
});

How do I get it work on all browsers?

Appreciate your help.

Anonymous said...

Has there been anyone who's been able to figure out a way to "sort" the 2nd list?

Also, I use options grouping...

I am only able to move [options] to the right column, but how can I make sure the options are appended to the correct [optgroup] ?

adana web tasarim said...

There are two css classes used, one for the overall div & the other for the individual boxes, so I set defaults for those. The 'selectN' value is either itself or (n-1), so as long as I step up by even numbers, the function won't overlap. Other than remembering which N is which when prepping for db insert, it's now total piece of cake. Good thing, too, since I'll be reusing this function too many times to count in this app.

eticaret said...

No…it doesnt work in explorer. anyone got an idea about runnig this along prototype?

Andreas said...

Excellent post. Helped me a lot at work today, thanks!

V i a n said...

another saved live,
another saved code,
its me and my beloved program :)
many thanks

Anonymous said...

Using PHP how can I show the selections the user has already made. The slection that get moved into selectionbox 2, once submitted get stored in mysql table. So I want to echo the options they have selected in that second list

LRod said...

Great tutorial.
As I used ASP.NET I don't get the submit button, I have an update button that calls a proc and save the data in to the database, but how can i achieve to store the items on second list, save it and also display when user gets back?
any ideas?
Thank you in advanced.

oscarfg said...

Great code.

Is it possible to add selected options to the right-list but without removing them from the left-list?

Thanks!

Desarrollo Web said...

thanks, really usefull.

also, thanks charlie ;)

Juanca

Erik Juhlin said...

Thanks for the code! Since I wanted to trigger move on double click also, I made a little function to help me do the move:
$.fn.moveSelectedTo = function (selector) {
this.find("option:selected").remove().appendTo(selector);
$(selector).sortOptionsByText();
};

I also added the sorting with this function:
$.fn.sortOptionsByText = function() {
var options = $("#" + this.attr('id') + ' option');
options.sort(function(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
else return 0;
});

this.empty().append(options);
return options;
};

This can be used like this:
$('#add').click(function () {
$('#select1').moveSelectedTo('#select2');
});

Anonymous said...

It not works if I use

"May want to add you name="Select2[]"
to handle multiple selections in the $_POST"

only takes the first value because the id is id="Select2" with out [] to run the jquery and not declared as an array.
Anyone else have this problem in PHP?
Thanks

Nick

Xnetwork said...

Ok, after pulling quite a few small bundles of hair from my weary skull I finally discovered why values weren't transmitted upon hitting the submit button. They have to be selected by the user in the browser, just adding 'selected' to the option tag won't cut it. Doh! As always the solution to this is maddening easy, I solved my woes with this code:

$('input[@type=submit]').click(function() {
$('#select2 *').attr('selected','selected');
});

hth,

ap

Ps. thanks a bunch for your jquery code, you really should make it into a nice manageable jquery plugin... Great addition to my toolbox :D

Kurumsal Tasarım said...

Not to take away from your script, but if we're handling the events inline, then jQuery let's me do this function in one line:

function moveFromTo(fromId, toId) { return !$('#'+fromId).children('option:selected').remove().appendTo($('#'+toId)); }

:p

stor perde said...

Could you please contact me about this article? I'd like to talk to you about promoting this article to a larger audience.

tindel said...

This was referenced briefly before, but here it is again, because I wan't able find it quickly:

I preferred to not remove the data in the original selector, so I used the following code instead:

return !$('#select1 option:selected').clone().appendTo('#select2');

Anonymous said...

thank you very much it helped a lot

justin

Anonymous said...

Does anyone know how to retain the original order of the selected items after submitting?

The best solution I can think of is sorting the ul.selected using jQuery and some value containing the submitted order - but not sure how to do this.

Anonymous said...

This post is really helpful but how to get values in post if I am using AHAH. I am not able to add below code before ahah call.

$("form").submit(function() { $('#select2').each(function(){
$('#select2 option').attr("selected","selected");
});


can any one help me in this ?

DanaLapid said...

For the commenter who said "It's formatting ok and the php is filling in the selects but it's not passing from contbox1 over to contbox2"

You should try using a php code generator, it worked for me.

André Silva said...

I've found this post to very helpful, however, I am trying to do form validation before submiting, and I need the Select box on the right to be of minimum length.

$("select#select1 option").length is giving the right number of options, however, the same function applied to the select2 (the one on the right side) always returns 0.

What's the issue here? Thank You.

Abhilash said...

is it free to use in commercial projects

Matheus said...

What if i'm using a select multiple with optgroups?

Chandro Roy said...

Great work,thank you for information

kapitan said...

nice! nice!
exactly what im loking for! the added code to select everything on select2 onsubmit helped a lot too!

Clipping Path said...

Interesting article and this point hadn't occurred to me. As I think a lot of male detectives are also represented as being damaged in some way.

Web Tasarımı said...

thanksssssss

Ureticy said...

Thank you so much

ekram said...

This post is very helpful.. I want to bookmark this post. I will apply this for my clipping path service related site.

essay said...

Your write-up is pretty helpful! Looking at your work has educated me. Discovered a lot from it. I will favorite your blog and will consistently browse your forthcoming blog posts. Awesome! Kudos!

Sikkandar Bhooto Jahir Hussain said...

i have added the values select1 listbox to select2 listbox.if i click inside the select2 listbox on any value that only get focused and submitted. but what i need is to post all the values in select2 listbox. is it possible. simply say the second list box values loosing the focus.

Adrian Tadeo said...

hi how can i connect this and save to the database tnx:)

Anonymous said...

Hi,

I just wanted to say that the form submission code:
$('form').submit(function() {
$('#select2 option').each(function(i) {
$(this).attr("selected", "selected");
});
});

Won't work under jquery 1.10.1. You will have to use the "prop" function instead as follows:

$('form').submit(function() {
$('#select2 option').each(function(i) {
$(this).prop("selected", "selected");
});
});

See a working JSFiddle here:
http://jsfiddle.net/jakecigar/a8qaC/2

Best regards
Josef

Celil Can said...

Thank you so much, very nice article
Please visit : http://www.celilcan.com

gömlek said...

Thank you very nice tutorial

అనిల్ రెడ్డి said...

Very simple, straight forward solution that I was looking for and which I can stylize in my own way further by using CSS! Thanks a ton!

Clipping Path Center said...

thanks for the post

Chyou Ma said...

WOW, it is a great post
clipping paths

jui fardin said...

Your post is very nice. By your post i learn many things like how can i select, delete .... and your cooding part is excellent.
clipping paths

Linda J. Prieto said...

It is very informative post so i like this post very much.
photo retouching

Roger M. Lloyd said...

It is very informative post so i like this post very much.
clipping mask

Jason B. Mixon said...

I like your blog very much. Keep up this great job.

image manipulation

Ethnic Food said...

Awesome and amazing article.

Makayla Charleston said...

You have done such an amazing job on this series. I envy your sewing skills and your patience and your diligence. If anyone ever asks me how to sew, I'm sending them to your blog and this series. Congratulations on such an extensive, well thought out and clearly presented set of tutorials
clipping path

get rid of cellulite said...

Thanks, this is in every respect what I need to know. Thank you, it's very interesting. I wish you all the best and every success in future.
Energiefonds

Aanrechtblad said...

This website has very good content. Thank you for the great article I did enjoyed reading it, I will be sure to bookmark your blog and definitely will come back from again

mindfulness courses said...

I have no words to appreciate this post ..... I'm really impressed with this post .... the person who created this post was a big thank you man .. for sharing with us.

Catalina G. Obrien said...

It was certainly interesting for me to read that article. Thanx for it. I like such topics and anything that is connected to this matter. I definitely want to read more on that blog soon.really good job .... Hats off mann
clipping path

trap said...

This website has very good content. Thank you for the great article I did enjoyed reading it, I will be sure to bookmark your blog and definitely will come back from again