Monday, April 9, 2012

How to filter GridView records using jQuery

Yesterday, I got into a situation where I need to filter the rows/records of the ASP.NET GridView on client side. When I say filter, that means depending on some condition just show only those records which satisfies the condition. And I implemented the same using jQuery so thought of sharing with you.

Problem:

First take a look at below image.


As you can see from image, that there is a GridView control populated with data and above that there are link buttons for each alphabet along with "All" button. So the problem was, based on the clicked button filter the data from GridView on "ProductName" column. For example, if "H" is clicked, only those products should be visible whose name starts with "H".


And if there are no records that satisfies the condition, then display no records message.


Note: Following controls are placed on the page.
  • A GridView
  • A Label control which has "No records to display" message.
  • And separate link button for each alphabet and one link button for "All".

Solution:

To implement this feature the solution is,
  • When DOM is ready then hide the Label control.
  • Attach click event for Link buttons. I have assigned a class "links" to all link button. So using class selector, we can attach the click event.
  • Get the text of the clicked button.
  • Now loop through all the gridviews rows and find td with Product Name.
  • Check if the text of td starts with cliked button's text.
  • If yes, then don't hide the row. Otherwise, hide the row.

But we also need to handle the "All" button code and when there are no records then show the label control. The code is very much self explanatory.
//Code Starts
$(document).ready(function() {
    $('#<%=lblNoRecords.ClientID%>').css('display','none');

    $('.links').click(function(e)
    {
        $('#<%=lblNoRecords.ClientID%>').css('display','none'); 

        var lnkText = $(this).text().toLowerCase();
        var iCounter = 0;

        $("#<%=gdRows.ClientID%> tr:has(td)").each(function() {
            var cell = $(this).find("td:eq(1)").text().toLowerCase();
            if(lnkText != 'all')
            {
                if(cell.indexOf(lnkText) != 0)
                {
                    $(this).css('display','none');
                }
                else
                {
                    $(this).css('display','');
                    iCounter++;
                }    
            }
            else
            {
                $(this).css('display','');
                iCounter++;
            }
        });

        if(iCounter == 0)
        {
            $('#<%=lblNoRecords.ClientID%>').css('display','');
        }
        e.preventDefault();
    });
});
//Code Ends
Also read GridView Tips and Tricks using jQuery

Feel free to contact me for any help related to jQuery, I will gladly help you.