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: 38585
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="http://www.dotnetcurry.com/ShowArticle.aspx?ID=403">51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls
    </a>
    <br /><br />
    Visit <a href="http://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  
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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>

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel