Search and Filter Items of an ASP.NET DropDownList using jQuery
Rating: 2 user(s) have rated this article Average rating: 5.0
Posted by: Suprotim Agarwal, on 10/31/2009, in category "jQuery and ASP.NET"
Views: this article has been read 7317 times
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.
I hope you liked this article and I thank you for viewing it. This article was 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 

Note: - Our code download (if any) has a password which is available to our Registered members as well as Newsletter Subscribers.








Follow me on twitter

Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Jon on Monday, November 02, 2009 2:46 PM
Why do you use "$('input[id$=txtNew]')" instead of "$('input#txtNew')"
??
Comment posted by Suprotim Agarwal on Wednesday, November 04, 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 09, 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!!

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


Latest Articles

Using BindAttribute In ASP.NET MVC To Exclude Bindable Data

Change Image Opacity on MouseOver using jQuery

Click and Increase the Size of an Image using jQuery

20 Must Read LINQ, WCF, Expression Web, VSTS and Windows Forms articles on DotNetCurry – 2009

Using jQuery To Hijack ASP.NET MVC Form Posts



Top Articles

Some ASP.NET GridView UI Tips and Tricks using jQuery

SQL Cache Dependency with SQL Server, LINQ and ASP.NET 3.5

GridView Tips and Tricks using ASP.NET 2.0

Delete Multiple Rows In A GridView

How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript



Top Authors

Suprotim Agarwal(210)

Minal Agarwal(69)

Malcolm Sheridan(61)

Subodh Sohoni(29)

Mahesh Sabnis(16)



Translate Page




Advertise on this site through Lake Quincy Media



Login

 
 
 


Author of the Month

Categories



Connect With Us
Just started Tweeting - Help us Grow

ASP.NET MVP Award 2008


Announcement
Congratulations to our author Minal for becoming a Microsoft MVP in the Expression Web category.