Pages

Thursday, May 24, 2012

Convert ASP.NET DropDownList into Multi Select ListBox using jQuery


In this simple article, we will see how to convert an ASP.NET DropDownList into Multi Select ListBox, in order to select multiple items. This article is a chapter from my EBook called 51 Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article and use the latest jQuery version.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. It’s also always best to choose appropriate server side controls at the time of designing the application. If the user turns off JavaScript in his browser, the jQuery code won't work. So use this example with caution. The code shown below has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
Multiple items cannot be selected in a DropDownList unless you change the default behavior of this control by writing custom code. It’s the ListBox control that allows the user to select multiple items when its ‘SelectionMode’ property is set to multiple.
I faced this requirement recently during a client visit. The client was keen on keeping a DropDownList to save screen space. However they also wanted to convert the DropDownList to a ListBox, if the user wanted to select multiple items. So to solve this requirement client-side, a jQuery was used to 'make it appear' that we are converting the DropDownList to a MultiSelect ListBox control on the click of a Button. Let us see the entire code first
Convert DropDownList jQuery 
As you can see, to convert the DropDownList to a MultiSelect ListBox control on the click of a Button, we just requires a single line of jQuery code as shown here:
DropDownList To ListBox 
Once the DropDownList is converted into a ListBox control, the user can select multiple items and list them by using the code shown below
Multiple Select DropDown jQuery 
Before the Button is clicked, the output looks like this:
DDL Button Click 
After the Button is clicked, the DropDownList is converted to a Multi Select Listbox as shown below:
MultiSelect DropDownList jQuery 
After the user selects multiple values and clicks the Button, the output changes as shown here:
Select Multiple Items jQuery 
See a Live Demo 

I hope you found this article useful and I thank you for viewing it. This article was taken from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which contains similar recipes that you can use in your applications.
The entire source code of this article can be downloaded over here

No comments:

Post a Comment