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 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 elements side by side with two buttons between them. Here's what it looks like:
< form method ="get">
< select id ="SelectLeft" multiple ="multiple">
< option value ="1"> Australiaoption >
< option value ="2"> New Zealandoption >
< option value ="3"> Canadaoption >
< option value ="4"> USAoption >
< option value ="5"> Franceoption >
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 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(' + e.value + '">' + e.text + ' '); }); $(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(' + e.value + '">' + e.text + ' '); }); Then I append it to the end of the 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 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
Posted by
Ananth
at
3:43 am
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
About Me
Ananth
View my complete profile
Blog Archive
►
2011
(4)
►
March
(2)
►
February
(1)
►
January
(1)
▼
2010
(217)
►
November
(2)
►
October
(1)
►
September
(6)
►
August
(18)
▼
July
(166)
How to compress ViewState In ASP.NET
GridView Tips and Tricks using ASP.NET
ASP.NET AJAX Interview Questions – Part I
Programmatically Encrypt and Decrypt Configuration...
Are You A Good Developer?
Some Common Conversion Functions
30 Common String Operations in C# and VB.NET – Part I
Some ASP.NET GridView UI Tips and Tricks using jQuery
ASP.NET DropDownList with Custom Paging
Displaying SQL Server Messages using ASP.NET and A...
Ajax Control Toolkit 3.5
Using the ValidationSummary control with ASP.NET M...
Limit Number Of Characters In an ASP.NET Multiline...
Prevent Cut, Copy and Paste Operations in an ASP.N...
Create an ASP.NET TextBox Watermark Effec...
Click and Retrieve the Value of a GridView Cell us...
Keeping Your ASP.NET Session Alive Using jQuery
Moving data between two ListBoxes - Difference bet...
What's New in ASP.NET 4.0 - ClientID Generation fo...
TextBox AutoComplete with ASP.NET and jQuery UI
ASP.NET Page Curls using jQuery
Using Script reference Profiler to Improve the Per...
Shift Focus to the Next TextBox using the Enter Ke...
Creating Report in Business Intelligence Developme...
Cancelling an Asynchronous PostBack in ASP.NET Ajax
SQLike – a small query engine
Why ASP.NET AJAX UpdatePanels are dangerous
Are you making these 3 common ASP.NET AJAX mistakes?
Issues in AJAX UpdatePanel
Check whether the pop up blocker is enabled or not
Javascript to disable a particular key
ASCII Key Values
width and height of the client window
SPEED UP UR ACROBAT READER (ALMOST LIKE NOTEPAD)
Hidden Bluetooth service in Windows XP and Vista..
<asp:content id="ContentLogin" contentplaceholder...
Javascript
Google Search tips
Wanna Hack Google To Do Cool Stuff :--
Use Google to get Serial No of any Software
SMARTSQL CLASS VB.NET Version Version 1.00
check-uncheck-checkboxes-in-gridview-using-javascript
156 Run Commands for window Software & Third Party...
How to insert an image in Access Database?
What are the important points when developing a da...
How do I write common code for different dot net f...
How do I update the physical database with the cha...
How do I update the dataset with the updates in re...
Database Connection String Formates for .NET, Java...
Connection String
Writing/Developing Facebook Applications in .NET u...
Alternative to TOP in SQL Server and Oracle.
T-SQL Debugger is back in SQL Server 2008 ... debu...
New Features in SQL Server 2008 Management Studio ...
Saving changes is not permitted. The changes that ...
DISPLAY A TOOLTIP FOR A DATAGRID CELL
DROPDOWN COUNTRIES
ENCRYPTION OF STRING
GRIDVIEW MOUSEOVER COLOR
CHECK FOR COOKIE ACCEPTANCE
STRING TO DATETIME WITH SPECIFIC FORMAT
ALPHABET LIST
SCROLL TO THE BOTTOM OF A TEXT BOX CONTROL PROGRAM...
PAGENAMEFROMURL
START/END DATES
MONTHNAME FROM INT
EXTRA SPACES BETWEEN WORDS IN DROPDOWNLIST
VALIDATE STRING VIA REGULAR EXPRESSION
ROWFILTER
QUERYSTRING CHECK
C# ISDATE FUNCTION
C# ENCODE URL STRING
REPLACE QUERY PARAMETER VALUE
EXTENSION METHOD TO TEST WHETHER A STRING IS NULL ...
C# STRING FORMATS
FINDING OTHER CONTROLS IN SAME GRIDVIEW ROW FROM T...
SIMPLE DELEGATE EXAMPLE
GET NUMBER FROM STRING
DELETE FILES OLDER THAN X-AMOUNT OF TIME
OPEN WEB BROWSER
DISABLE BUTTON ON POSTBACK
AUTOMATICALLY SHOWING A WAIT CURSOR TO INDICATE A ...
GETTING ID OF INSERTED ROW
PAGINATION IN SQL
THE DIFFERENCE BETWEEN <%= AND <%# IN ASP.NET
CREATING A DATASET FROM SCRATCH
BASIC INSERT AND SELECT COMMANDS FOR SQLITE IN .NET
CONVERT LOWERCASE AND UPPERCASE TO TITLECASE IN .NET
CONVERTING METHODINFO INTO A DELEGATE INSTANCE TO ...
SETTING ACTIVE ITEM IN DROPDOWNLIST
GET COUNTRIES LIST
HIDE MINIMIZE AND MAXIMIZE BUTTONS
ADD INDEX NUMBERS TO EACH ROW HEADER IN A DATAGRID...
LISTVIEW WITH RE-ORDERING THROUGH DRAG AND DROP
IN & NOTIN EXTENSION METHODS
CONSTRUCTING GENERICS THROUGH REFLECTION (LIST OF ...
BASIC AUTHENTICATION (FOR GOOGLE CHECKOUT)
CAUSE A POSTBACK IN .NET
ASP.NET SESSION STATE, COOKIES AND SUBDOMAINS
LISTBOX DRAG SCROLL
►
June
(24)
Followers
Simple theme. Theme images by gaffera. Powered by Blogger.