I have the following html table and jQuery function. I want to sort the table when user clicks on table headers. This works fine if the table column is text or number. But not working properly when the column is date type.
To sort the date column, what I was thinking of is to put the condition like this:
if(index === 3){//for date column sort...
} else {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
But couldn't really figure out how to sort the table when I have the date range in Date column. Any help would be greatly appreciated!
//sort table
$('th').click(function(){
//alert($(this).index())
$('th').css({'background-color' : '#cccccc'});
$(this).css('background-color', '#808080');
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
th{
background-color: #cccccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>S.No.</th>
<th>Number</th>
<th>Text</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100</td>
<td>Canada</td>
<td>01/06/2016 - 01/07/2018</td>
</tr><tr>
<td>2</td>
<td>3000</td>
<td>USA</td>
<td>12/08/2017 - 12/12/2017</td>
</tr><tr>
<td>3</td>
<td>1202</td>
<td>Mexico</td>
<td>12/09/2018 - 01/07/2018</td>
</tr><tr>
<td>4</td>
<td>20</td>
<td>Brazil</td>
<td>04/29/2018 - 05/01/2018</td>
</tr><tr>
<td>5</td>
<td>1680</td>
<td>Germany</td>
<td>04/29/2018 - 05/01/2018</td>
</tr>
</tbody>
</table>