Shane Buckley
Shane Buckley

Reputation: 134

Sort html table alphabetically on page load

I'm looking to sort a html table alphabetically on page load the same way you can sort an unordered list.

I tried to use the code below but did not work:

    var mylist = $('#myTable');
var listitems = mylist.children('tr').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

And then

<table id="myTable">
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/01/2016</td>
</tr>
</table>

I want it to sort the table alphabetically by the first column in a row.

I can't find anything about this online.

Upvotes: 2

Views: 7295

Answers (2)

tkay
tkay

Reputation: 1726

Here is a snippet that I use. note: This is faster than using jquery find()

function sortTable(){
    var table = document.getElementById("myTable");
    var Arr = [];
    for(var i=0, ln=table.rows.length; i<ln; i++){
        var row = table.rows[i];
        var firstCell = row.cells[0].textContent;
     Arr.push([firstCell, row]);  //temporary array
    }
//sort by first column of inner arrays
    Arr = Arr.sort(function(a,b) {
  return a[0] > b[0];
});
    for(var i=0, ln=Arr.length; i<ln; i++){
        table.appendChild(Arr[i][1]);
    }
    Arr = null;
}
sortTable();
<table id="myTable">
<tr>
<td>d</td>
<td>12/03/2016</td>
</tr>
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/04/2016</td>
</tr>
<tr>
<td>C</td>
<td>12/04/2016</td>
</tr>
</table>

Upvotes: 1

Sing
Sing

Reputation: 4052

Your problem is this line did not return your trs:

var listitems = mylist.children('tr').get();

Modify to below and everything will work.

var listitems = mylist.find('tr');

var mylist = $('#myTable');
var listitems = mylist.find('tr');
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/01/2016</td>
</tr>
</table>

Upvotes: 5

Related Questions