6

I wouldn't want to use plugin to sort my table such as tablesorter because it would be an overhead for desired functionality.

I want to sort my table only once when page is loaded I don't want that functionality to be available all the time.

So imagine if I have i rows each containing k columns and k #2 is the one I want to use for this sorting so my sorting would be based on this column in descending order I want to sort their rows.

Something like this :

        var $rows = $("#score-table tr");
            $.each($rows, function(index, row) {
                //sort table
            });
2
  • This one is verylightweight : joequery.github.io/Stupid-Table-Plugin Commented May 16, 2013 at 13:03
  • what do you want to sort it by? class name, id, text value, etc...? Commented May 16, 2013 at 13:44

1 Answer 1

15

Well if you know which column you are sorting on you can easily sort the table using javascript's sort function

var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){ 
    var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
    var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
            // if a < b return 1
    return tda < tdb ? 1 
           // else if a > b return -1
           : tda > tdb ? -1 
           // else they are equal - return 0    
           : 0;           
}).appendTo($tbody);

If you want ascending you just have to reverse the > and <

If they are just numbers you can just do a-b for ascending or b-a for descending

After the sort is complete just append it back to the body and your done

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.