Moving data between two ListBoxes - Difference between jQuery 1.3.2 and jQuery 1.4

Posted by: Malcolm Sheridan , on 2/4/2010, in Category ASP.NET MVC
Views: 85280
Abstract: The following article demonstrates the benefit in using jQuery 1.4 over 1.3.2 when you need to move data between two select elements.
Moving data between two ListBoxes - Difference between jQuery 1.3.2 and jQuery 1.4
 
Recently a new version of jQuery was released. This version is 1.4. As with any new version, ultimately you see what used to take you several lines of code, now rolled up into a single line of code. I'm going to demonstrate a question I've been asked many times on forums and that is how to move selected items from one<select> element to another. I'll show you how you could do it using jQuery 1.3.2 and how to minimize the code by using the new 1.4 library. Before we begin, the new version can be found here.
The HTML
The HTML for this is pretty straight forward. It's simply two <select> elements side by side with two buttons between them. Here's what it looks like:

 

Move data between two listboxes
<form method="get">             
      <select id="SelectLeft" multiple="multiple">
            <option value="1">Australia</option>
            <option value="2">New Zealand</option>
            <option value="3">Canada</option>
            <option value="4">USA</option>
            <option value="5">France</option>
      </select>
           
      <input id="MoveRight" type="button" value=" >> " />
      <input id="MoveLeft" type="button" value=" << " />
       
      <select id="SelectRight" multiple="multiple">          
      </select>
</form>
jQuery 1.3.2
Below is the code to move the selected items from each <select> element. 
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>   
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + "option:selected");
                var output = [];               
                $.each(selectedItems, function(key, e) {                   
                  output.push('<option value="' + e.value + '">' + e.text + '</option>');
                                });
               
                $(moveTo).append(output.join(""));               
                selectedItems.remove();
            });
        });
    </script>
I've bound one event handler for the button clicks. To decide which direction the selected items should go, I'm using the ID of the button that fired the event:
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
Next I create an empty array and loop through every selected item and add it to the end of the array:
 
var output = [];               
$.each(selectedItems, function(key, e) {                   
      output.push('<option value="' + e.value + '">' + e.text + '</option>');
});
 
Then I append it to the end of the <select> element and remove the moved items:
$(moveTo).append(output.join(""));               
selectedItems.remove();
 
Overall I think that's a good approach. In jQuery 1.4 we can make this better!
 
jQuery 1.4
 
In the new jQuery library, the team has introduced a new function called toArray. This retrieves all the DOM elements contained in the jQuery set, as an array. So here's the code below:
 
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + " :selected").toArray();
                $(moveTo).append(selectedItems);
                selectedItems.remove;
            });
        });
    </script> 
 
The first thing you'll notice is the code has been reduced. Thanks to the toArray function, I have eliminated the need to loop through the selected items. Now they're returned as an array:
 
var selectedItems = $(selectFrom + " :selected").toArray();
 
And to add them to the <select> element, I no longer need to use the join function, I simply append them:
 
$(moveTo).append(selectedItems);
 

 Nice and simple! The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Ranesh on Sunday, February 7, 2010 5:00 AM
how to show data in page load time when we create list box in mvc plz give right answer becoz i m beginner in mvc asp.net
Comment posted by Ruben on Monday, February 8, 2010 1:28 PM
this line is wrong:
var selectedItems = $(selectFrom + " :selected");

should be:

var selectedItems = $(selectFrom + " option:selected");
Comment posted by Malcolm Sheridan on Monday, February 8, 2010 11:02 PM
@Ruben
Good point.  I forgot that.
Comment posted by Dazzle on Thursday, March 11, 2010 10:43 AM
good article
Comment posted by Ryan on Monday, August 23, 2010 10:09 PM
Very helpful, thanks.

It would be nice if you included code that will pass the whole list to the server.  Normally in a select only the "selected" elements are passed.  On submit you need to grab all the data from one (or both depending on what you are trying to do) select and put it in a hidden field or something so your server side code can retrieve it.
Comment posted by Jesús Ángel del Pozo on Wednesday, August 25, 2010 11:46 AM
Even shorter:

jQuery(selectFrom + " option:selected").remove().appendTo(moveTo);

And it works with jQuery 1.3 too.
Comment posted by Jesús Ángel del Pozo on Wednesday, August 25, 2010 11:56 AM
@Ryan

A quick fix to send all select's options:

jQuery('#submitButtonId').click(function() { jQuery('#SelectRight option').attr('selected', 'selected'); return true; });

Bye
Comment posted by Khai on Tuesday, March 22, 2011 10:56 PM
how do i keep the listboxes sorted?  

var selectedItems = $(selectFrom + " option:selected").sortable('toArray'); //this throws an error
Comment posted by Sachin on Thursday, May 16, 2013 6:50 AM
var selectedItems = $(selectFrom + " :selected").toArray();

It has to be

var selectedItems = $(selectFrom + " option:selected").toArray();
Comment posted by Muhammad Mubashir. on Friday, June 14, 2013 2:12 AM
Marvelloue you saved our time. :-)
Comment posted by Gayatri on Wednesday, July 24, 2013 6:15 PM
I am trying to run same in eclipse using JSP it is not excecuting Move buttons properly? Is the there anything to import to make it work?
Comment posted by hh on Friday, March 7, 2014 5:08 AM
hhh
Comment posted by Kelder on Monday, August 11, 2014 10:01 AM
Khai was looking for a way to sort so here is a solution found on the link below.

function NASort(a, b) {
    if (a.innerHTML == 'NA') {
return 1;
    }
    else if (b.innerHTML == 'NA') {
return -1;
    }
    return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
$(moveTo + ' option').sort(NASort).appendTo(moveTo);

Author: http://stackoverflow.com/questions/6670041/sort-options-in-a-select-list-with-javascript-jquery-but-not-alphabetically#6670291
Comment posted by David Lambl on Monday, February 23, 2015 3:25 PM
Very helpful example. Thank you!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook