Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8287481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T12:03:27+00:00 2026-06-08T12:03:27+00:00

I have some code to sort a table in jQuery as shown below. $(document).ready(function()

  • 0

I have some code to sort a table in jQuery as shown below.

   $(document).ready(function() {
        //grab all header rows
        $('thead th').each(function(column){
            $(this).addClass('sortable').click(function() {
                var findSortKey = function($cell) {
                    return $cell.find('.sort-key').text().toUpperCase()
                    + ' ' + $cell.text().toUpperCase();
                };

                var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;

                //step back up tree and get the rows with data
                //for sorting
                var $rows = $(this).parent().parent().parent().find('tbody tr').get();

                //loop through all the rows and find
                $.each($rows, function(index, row) {
                    row.sortKey = findSortKey($(row).children('td').eq(column));
                });

                //compare and sort the rows alphabetically or numerically
                $rows.sort(function(a, b) {
                    if (a.sortKey.indexOf('-') == -1){
                        if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
                            return -sortDirection;
                        }
                        if (parseInt(a.sortKey) > parseInt(b.sortKey)) {
                            return sortDirection;
                        }
                    } else {

                        if (a.sortKey < b.sortKey) {
                            return -sortDirection;
                        }
                         if (a.sortKey > b.sortKey) {
                            return sortDirection;
                        }
                    }

                    return 0;
                });

                //add the rows in the correct order to the bottom of the table
                $.each($rows, function(index, row) {
                    $('tbody').append(row);
                    row.sortKey = null;
                });

                //identify the column sort order
                $('th').removeClass('sorted-asc sorted-desc');
                var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
                sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');

                // identify the column to be sorted by
                $('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');

                //$('.visible td').removeClass('odd');
                //zebraRows('.vi')
            });
        });
    });

Also the css

root { 
    display: block;
}

th.sortable {
    color: #666;
    cursor: pointer;
    text-decoration: underline;

}
th.sortable:hover{color:black;}
th.sorted-asc, th.sorted-desc { color:black;
          background-color: cadetblue;
}

This works for one table, but not for multiple tables. Is there any way I could do this based on the ids of the divs the tables are nested in?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T12:03:28+00:00Added an answer on June 8, 2026 at 12:03 pm

    Some of the selectors need to be made specific to the table in question.

    By progressive improvement, I arrive at the following :

    $(document).ready(function() {
        function findSortKey($cell) {
            return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
        };
        function sortFn(a, b) {
            if (a.sortKey.indexOf('-') == -1) {
                return parseInt(a.sortKey, 10) - parseInt(b.sortKey, 10);
            } else {
                return a.sortKey - b.sortKey;
            }
        }
        $('thead th').each(function(column) {
            $(this).addClass('sortable').click(function() {
                var $th = $(this);
                var sortDirection = $th.is('.sorted-asc') ? -1 : 1;
                var $tbody = $th.closest('table').children('tbody');
                var rows = $tbody.children('tr').get();
                $.each(rows, function(index, row) {
                    row.sortKey = findSortKey($(row).children('td').eq(column));
                });
                rows.sort(function(a, b) {
                    if(sortDirection == 1) { return sortFn(a, b); }//sort asc.
                    else { return sortFn(b, a); }//reverse a and b to sort desc.
                });
                $.each(rows, function(index, row) {
                    $tbody.append(row);
                    row.sortKey = null;//??
                });
                var filterSelector = ':nth-child(' + (column + 1) + ')';
                $th.removeClass('sorted-asc sorted-desc').filter(filterSelector).addClass( (sortDirection == 1) ? 'sorted-asc' : 'sorted-desc' );
                $tbody.children('td').removeClass('sorted').filter(filterSelector).addClass('sorted');
            });
        });
    });
    

    untested, so may need debugging

    Apart from correcting the selectors, the most significant changes are to pull a couple of functions outside the outer each() loop and to simplify the sort function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'd like some help with the following jQuery code if possible... $(document).ready(function() { $('table.sortable').each(function()
I have some simple jQuery code: var response = Array() $('.task-list').each(function() { response.concat(response,$('#' +
I have some old code that uses qsort to sort an MFC CArray of
I have some PHP code which allows me to sort a column into ascending
I have some code that sorts table columns by object properties. It occurred to
I have some code that builds SQL queries to perform a lenient, catch-all kind
In my Rails app I have some plain old JS: function reorder(divid,url) { jQuery(divid).sortable({
I have some code on two systems running kernel 2.4.20 and kernel 2.4.38 .
I have some code that will change the background color of a specific label
I have some code here that uses bitsets to store many 1 bit values

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.