Search and Filter Items of an ASP.NET DropDownList using jQuery

Posted by: Suprotim Agarwal , on 10/31/2009, in Category jQuery and ASP.NET
Views: 46123
Abstract: In this short article, I will demonstrate how to search and filter items of an ASP.NET DropDownList using jQuery.
Search and Filter Items of an ASP.NET DropDownList using jQuery
 
In this short article, I will demonstrate how to search and filter 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.
 
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 search and filter items of a DropDownList
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Search and Filter a DropDownList</title>
    <script src="Scripts/jquery-1.3.2.min.js"
        type="text/javascript"></script>
   
    <script type="text/javascript">
        $(function() {
            var $txt = $('input[id$=txtNew]');
            var $ddl = $('select[id$=DDL]');
            var $items = $('select[id$=DDL] option');
 
            $txt.keyup(function() {
                searchDdl($txt.val());
            });
 
            function searchDdl(item) {
                $ddl.empty();
                var exp = new RegExp(item, "i");
                var arr = $.grep($items,
                    function(n) {
                        return exp.test($(n).text());
                    });
 
                if (arr.length > 0) {
                    countItemsFound(arr.length);
                    $.each(arr, function() {
                        $ddl.append(this);
                        $ddl.get(0).selectedIndex = 0;
                    }
                    );
                }
                else {
                    countItemsFound(arr.length);
                    $ddl.append("<option>No Items Found</option>");
                }
            }
 
            function countItemsFound(num) {
                $("#para").empty();
                if ($txt.val().length) {
                    $("#para").html(num + " items found");
                }
 
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Enter Text in the TextBox to Filter the DropDownList </h2>
        <br />
        <asp:TextBox ID="txtNew" runat="server"
            ToolTip="Enter Text Here"></asp:TextBox><br />
        <asp:DropDownList ID="DDL" runat="server" >
            <asp:ListItem Text="Apple" Value="1"></asp:ListItem>
            <asp:ListItem Text="Orange" Value="2"></asp:ListItem>
            <asp:ListItem Text="Peache" Value="3"></asp:ListItem>
            <asp:ListItem Text="Banana" Value="4"></asp:ListItem>
            <asp:ListItem Text="Melon" Value="5"></asp:ListItem>
            <asp:ListItem Text="Lemon" Value="6"></asp:ListItem>
            <asp:ListItem Text="Pineapple" Value="7"></asp:ListItem>
            <asp:ListItem Text="Pomegranate" Value="8"></asp:ListItem>
            <asp:ListItem Text="Mulberry" Value="9"></asp:ListItem>
            <asp:ListItem Text="Apricot" Value="10"></asp:ListItem>
            <asp:ListItem Text="Cherry" Value="11"></asp:ListItem>
            <asp:ListItem Text="Blackberry" Value="12"></asp:ListItem>
        </asp:DropDownList>
        <br />
        <p id="para"></p>
        <br /><br />
        Tip: Items get filtered as characters are entered in the textbox.
        Search is not case-sensitive
    </div>
 
    </form>
</body>
</html>
 
The example starts by caching the following objects into variables
var $txt = $('input[id$=txtNew]');
var $ddl = $('select[id$=DDL]');
var $items = $('select[id$=DDL] option');
On the keyup() event of the textbox, we are calling the searchDdl() method which accepts the textbox value as its parameter.
$txt.keyup(function() {
    searchDdl($txt.val());
});
Inside the searchDdl() method, the contents of the DropDownList are emptied and we then use the RegExp object to store the search pattern. In this case, the search modifier is ‘i’ which tells the regular expression to ignore the case of the characters. The expression gets translated to /searchtext/i
Let us analyze this piece of code given below:
var arr = $.grep($items,
    function(n) {
        return exp.test($(n).text());
    });
 
The $.grep() method finds the elements of an array which satisfy a filter function. The syntax is as follows:
$.grep( array, callback, [invert] )
where the array refers to the set of <option> elements that are searched, and the callback refers to the function to process each item against. In this callback function, we call the .test() method of the RegExp object, passing it the option item text to see if it matches the characters entered by the user. The .grep() this way returns a newly constructed array containing a list of matched items, shown in the code above.
If the array contains matched items, the $.each() iterates over this collection(returned by the $.grep() method) and fires a callback function on each item, which appends the item to the DropDownList. The number of items that match the search are displayed using countItemsFound() function.
if (arr.length > 0) {
    countItemsFound(arr.length);
    $.each(arr, function() {
        $ddl.append(this);
        $ddl.get(0).selectedIndex = 0;
    }
    );
}
else {
    countItemsFound(arr.length);
    $ddl.append("<option>No Items Found</option>");
}
If the search does not match the items in the DropDownList, we display ‘No Items Found’ using the following code:
$ddl.append("<option>No Items Found</option>");
This is how we search and filter through the list.
Before the user type’s text in the TextBox, the output looks similar to the following:
BeforeSearch
After the user types some text in the TextBox, the output is as shown below:
AfterSearch
Tip: If you want to reverse the filter condition, use the [invert] attribute of the $.grep() method. For e.g. if you want to filter the DropDownList with items that ‘do not match’ the text entered by the user, use the [invert] attribute as shown below. This attribute takes a Boolean value.
var arr = $.grep($items,
    function(n) {
        return exp.test($(n).text());
    }, true);
 
You can see a Live Demo of this article. You can also download the entire source code of this article from here.
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 Jon on Monday, November 2, 2009 2:46 PM
Why do you use "$('input[id$=txtNew]')" instead of "$('input#txtNew')"
??
Comment posted by Suprotim Agarwal on Wednesday, November 4, 2009 3:00 AM
Jon: Because this way, the same code can be used on ASP.NET pages as well as Master pages. Remember the Client-Id mangling when dealing with controls on MasterPages :-).
Comment posted by Fajeo on Wednesday, December 9, 2009 5:49 AM
Nice article. Thanks for a solution that works on master pages
Comment posted by Ravi on Friday, December 11, 2009 8:41 AM
using masterpage this is not working
Comment posted by A-Dubb on Friday, December 11, 2009 12:10 PM
great article!!
Comment posted by pooja on Monday, January 4, 2010 2:30 AM
the code is very useful for me. but there is a problem.i have 10,000 items in dropdownlist.whenever i type a single character in textbox ,it start to search and take too much time.can i not use a search button in this code.i mean to say first i type in textbox and click on button then it will start io search.
                                                        thanks
    
Comment posted by Suprotim Agarwal on Tuesday, January 5, 2010 3:49 AM
Pooja: Yes it can be done on a button click. Instead of the keyup function, use the button click event.
Comment posted by makesh on Friday, June 7, 2013 3:16 AM
sir it is nice code aditionaly how i add when i enter id in number in txtbox  
the item filter in dropdown. please help me
Comment posted by kavita chougule on Wednesday, July 16, 2014 2:48 AM
can it work after postback of the same dropdown list?

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