Sort the Items of an ASP.NET DropDownList using jQuery

Posted by: Suprotim Agarwal , on 11/6/2009, in Category jQuery and ASP.NET
Views: 45926
Abstract: This short article demonstrates how to sort the items of an ASP.NET DropDownList using jQuery.
Sort the Items of an ASP.NET DropDownList using jQuery
 
This short article demonstrates how to sort the items of an ASP.NET DropDownList using jQuery. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls and has been modified to post it as an article.

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.
Let us quickly jump to the solution and see how we can sort the items of an ASP.NET DropDownList using client-side code. This example uses the latest minified version of jQuery which is 1.3.2 that can be downloaded from here. This example assumes that you have a folder called "Scripts" with the jQuery file (jquery-1.3.2.min.js) in that folder.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Sort Items of an ASP.NET DropDownList</title>
    <script src='../Scripts/jquery-1.3.2.min.js'
        type='text/javascript'>
    </script>
 
    <script type="text/javascript">
        $(function() {
            $('input[id$=btnSort]').click(function(e) {
                e.preventDefault();
                var sortedDdl =
                $.makeArray($('select[id$=DDL] option'))
                .sort(function(o, n) {
                    return $(o).text() < $(n).text() ? -1 : 1;
                });
                $("select[id$=DDL]").html(sortedDdl).val("1");
                $("#para").html("Items were Sorted!");
                $(this).attr("disabled", "disabled");
            });
        });
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Click on the Sort Button to Sort the DropDownList </h2>
        <asp:DropDownList ID="DDL" runat="server" >
            <asp:ListItem Text="Item3" Value="3"></asp:ListItem>
            <asp:ListItem Text="Item1" Value="1"></asp:ListItem>
            <asp:ListItem Text="Item4" Value="4"></asp:ListItem>
            <asp:ListItem Text="Item5" Value="5"></asp:ListItem>
            <asp:ListItem Text="Item2" Value="2"></asp:ListItem>
        </asp:DropDownList>
        <br /><br />
        <asp:Button ID="btnSort" runat="server" Text="Sort" />
        <p id="para"></p>
        <br /><br />
        Tip: Items are sorted in an Ascending order
    </div>
    <br /><br /><br /><br /><br /><br />
    <div id="divDemo" class="w2">
    This demo is from my EBook
    <a href="https://www.dotnetcurry.com/ShowArticle.aspx?ID=403">51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls
    </a>
    <br /><br />
    Visit <a href="https://www.dotnetcurry.com/BrowseArticles.aspx?CatID=63">DotNetCurry</a> and
    <a href="http://www.devcurry.com/search/label/jQuery">DevCurry</a> for more tips and tricks on jQuery
    and ASP.NET
    </div>   
    </form>
</body>
</html>
In the code shown above, when the user clicks on the Sort button, the <option> elements are converted to an array using $.makeArray().
$.makeArray($('select[id$=DDL] option'))
The JavaScript built-in sort() function is used on this array, which does an in-place sort of the array.
$.makeArray($('select[id$=DDL] option'))
.sort(function(o, n) {
    return $(o).text() < $(n).text() ? -1 : 1;
});
The final step is to empty the contents of the DropDownList and then use the .html() to replace the existing <options> with the sorted <options>.
$("select[id$=DDL]").empty().html(sorted)
The val("1") sets the first option as selected, after the sorting has been done.
When the page loads, the output looks similar to the following screenshot:
DropDownList_1
Before clicking on the Sort button, the output is as shown below:
DropDownList_2
After clicking on the Sort Button, the output is as shown below:
DropDownList_3
Tip: To sort in a descending order, replace this line
$(a).text() < $(b).text()
with this:
$(a).text() > $(b).text()
You can see a Live Demo over here.
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.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email  

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 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 eBook 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 .NET Standard and the upcoming C# 8.0 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
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by harishlavangade on Thursday, November 26, 2009 8:27 AM
It's very help for beginners.
Thanks
Comment posted by apekshit on Sunday, December 27, 2009 11:30 PM
I want to use multiple select drop down in my site <a href="http:ignou-student.blogspot.com"> http:ignou-student.blogspot.com </a>

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook