I've been struggling with this for a while and every time I test something I just end up getting different results.
JSFIDDLE
I have a basic table for test purposes with 3 entries that have 3 different headings to be sorted by: Name, Age, Date Joined.
Here is the table:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" id="firstName">name</th>
<th scope="col" id="age">age</th>
<th scope="col" id="date">date joined</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td class="firstName">Mark</td>
<td>12</td>
<td>12/02/2006</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="firstName">Jacob</td>
<td>30</td>
<td>03/04/2018</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="firstName">Larry</td>
<td>22</td>
<td>07/01/2009</td>
</tr>
</tbody>
Here is my JS:
function sortTable(column) {
var $tbody = $('.table tbody');
$tbody.find('td.' + column).sort(function(a,b){
var tda = $(a).find('td:eq(1)').text();
var tdb = $(b).find('td:eq(1)').text();
// 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);
}
$('#firstName').click(function() {
sortTable("firstName");
});
$('#age').click(function() {
sortTable("age");
});
$('#date').click(function() {
sortTable("date");
});
What I am trying to achieve
I want to be able to click each of the headers to sort the table by its respective content. So for example, when I click name it will sort by name. When I click age it will sort by age and when I click date joined it will sort by date.
I also really want to learn so I will give 100 bonus points for an answer that has good comments that can explain for me what is going on.
Thank you.
function sortTable(column) {
var $tbody = $('.table tbody');
$tbody.find('td.' + column).sort(function(a, b) {
var tda = $(a).find('td:eq(1)').text();
var tdb = $(b).find('td:eq(1)').text();
// 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);
}
$('#firstName').click(function() {
sortTable("firstName");
});
$('#age').click(function() {
sortTable("age");
});
$('#date').click(function() {
sortTable("date");
});
@import 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" id="firstName">name</th>
<th scope="col" id="age">age</th>
<th scope="col" id="date">date joined</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td class="firstName">Mark</td>
<td>12</td>
<td>12/02/2006</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="firstName">Jacob</td>
<td>30</td>
<td>03/04/2018</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="firstName">Larry</td>
<td>22</td>
<td>07/01/2009</td>
</tr>
</tbody>
</table>