Sorting Table Columns with jQuery


Background

I always heard about sorting table data & read lots of article that explain how to achieve it using jquery. You will also find lots of plugins available for sorting table data like Table sorter, Flexigrid , jqGrid and many more. Along with sorting feature it also support many more features like paging, resizable columns, cool themes, search and many more… But I feel that there must be one more feature in this library to sort table columns so that user will have full flexibility by playing with table arrangement along with column data. It might be possible that some of the library support this features or if not then planning to add it in their upcoming releases..

Sample Code

This code consist of GridView which shows Employee Name as Column along with some data. Now when user press sort button column will be sorted in ascending order along with data.

Here I have tried to achieve this features using some of the jQuery code without need of any library. Only thing we need here is jQuery library.

Step 1 : Add jQuery file Reference inside the tag of the page

<script src="Js/jquery-1.4.2.js" type="text/javascript"></script>

Step 2 : Next we need to drag and drop gridview on the page & set AutoGenerateColumns property to false. Specify the ID of the grid “gvEmployees”.

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" Width="500">
   <Columns>
      <asp:BoundField DataField="Sandeep" HeaderText="Sandeep" />
      <asp:BoundField DataField="Nishar" HeaderText="Nishar" />
      <asp:BoundField DataField="Dharmik" HeaderText="Dharmik" />
      <asp:BoundField DataField="Ravi" HeaderText="Ravi" />
      <asp:BoundField DataField="Jigish" HeaderText="Jigish" />
      <asp:BoundField DataField="Kapil" HeaderText="Kapil" />
   </Columns>
</asp:GridView>

Step 3 : Drag and drop one button on the page and give its ID=”btnSortColumn” and Text=”Sort Column”.

<asp:Button ID="btnSortColumn" runat="server" Text="Sort Column" />

Step 4 : write jQuery script for the button click event, which will sort table column along with data.

       $('#btnSortColumn').click(function() {

            //Get all the rows of employee grid
            var rows = $('#gvEmployees tr');

            //Start sorting column along with data
            rows.eq(0).find('th').sort(function(a, b) {

                return $.text([a]) > $.text([b]) ? 1 : -1;

            }).each(function(new_Index) {

                //Original Index
                var original_Index = $(this).index();

                //Reorder Header Text
                rows.each(function() {
                    var th = $(this).find('th');
                    if (original_Index !== new_Index)
                        th.eq(original_Index).insertAfter(th.eq(new_Index));
                });

                //Reorder Column Data
                rows.each(function() {
                    var td = $(this).find('td');
                    if (original_Index !== new_Index)
                        td.eq(original_Index).insertAfter(td.eq(new_Index));
                });

            });
            return false;
        });

Code itself explain lots of things,

Here ‘rows’ variable contain collection of Employee row. Next we find out the column name using header tag (th) and call the sort function of javascript to call the sorting mechanism.

rows.eq(0).find('th').sort(function(a, b)
{
    return $.text([a]) > $.text([b]) ? 1 : -1;
})

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

  • Less than 0: Sort “a” to be a lower index than “b”
  • Zero: “a” and “b” should be considered equal, and no sorting performed
  • Greater than 0: Sort “b” to be a lower index than “a”

To sort an array numerically and ascending for example, the body of your function would look like this:

function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}
th.eq(original_Index).insertAfter(th.eq(new_Index));

Will insert every table header element ( th ) from original place to new place.

td.eq(original_Index).insertAfter(td.eq(new_Index));

Will insert every table data element ( td ) from original place to new place.

Step 5 : Now we have done with aspx page coding , but what about data filling logic. here it goes. Call data biding function of the gridview in Page Load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Sandeep");
        table.Columns.Add("Nishar");
        table.Columns.Add("Dharmik");
        table.Columns.Add("Ravi");
        table.Columns.Add("Jigish");
        table.Columns.Add("Kapil");
        table.Rows.Add("20", "25", "45", "33", "22", "12");
        table.Rows.Add("40", "15", "15", "13", "12", "40");

        gvEmployees.DataSource = table;
        gvEmployees.DataBind();
    }

Here i have created dynamic datatable & filled some data rather than making Database connection & fetch data. but you can do what ever you want to bind grid.

Step 6 : Everything is setup now just press F5 & see the output of the page.

Before Sorting Column

After Sorting Column

Browser Support

I have tested this code on Firefox 3.6.8 & IE 8. you can also test it on any browser, i am sure that this code will run on all the latest browser.

Hope this will help !!!

Jay Ganesh

Reference

http://www.javascriptkit.com/javatutors/arraysort.shtml
http://api.jquery.com/insertAfter/

Shout it

kick it on DotNetKicks.com

About these ads

12 thoughts on “Sorting Table Columns with jQuery

  1. Pingback: DotNetShoutout

  2. Pingback: “Article of the Day” – ASP.NET Forum « Ramani Sandeep's Blog

  3. Pingback: dookudu trailer

  4. I should definitely say I’m impressed with your blog.
    I had no trouble navigating through all the tabs as well as related info.
    The site ended up being truly simple to access. Excellent job..

  5. gr8 post keep posting…
    i like it….
    can you please post on how to bind data get from js function to Gridview.

    thanks..
    Abhijit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s