Skip to content

Instantly share code, notes, and snippets.

@gujc71
Last active June 5, 2017 22:33
Show Gist options
  • Save gujc71/7d1746dd00be1bfd13a39a3c9eafb380 to your computer and use it in GitHub Desktop.
Save gujc71/7d1746dd00be1bfd13a39a3c9eafb380 to your computer and use it in GitHub Desktop.
js sample for table sorting
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='cache-control' content='no-cache'/>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Table Sorter</title>
<script src='https://code.jquery.com/jquery-3.2.1.slim.js'
integrity='sha256-tA8y0XqiwnpwmOIl3SGAcFl2RvxHjA8qp0+1uCGmRmg=' crossorigin='anonymous'></script>
<script>
/*
css and sorting field mark(▼▲).
*/
var data = [
['name', 'Java', 'Node', 'Perl'],
['Gu', 80, 70, 30],
['Kim', 90, 60, 80],
['Lee', 70, 70, 70],
['Brad', 50, 90, 90]
];
$(function() {
var table = $('<table>').css({'border': '1px solid', 'width': '300px'});
$('#targetPn').append( table );
$.each(data, function(inx, row ) {
var tr = $('<tr>');
table.append(tr);
$.each(row, function(inx, col ) {
var td = $('<td>');
tr.append(td.html(col));
});
});
table.find('tr:nth-child(1)').find('td').click(function() {
sortTable(this);
});
table.find('td').css({'border': '1px solid', 'width': '25%'});
});
function sortTable(cell){
$('table > tr:nth-child(1)').find('td').each(function(inx, td) {
td.innerHTML = td.innerHTML.replace(/[▼▲]/g, '') ;
});
var sortType = jQuery.data( cell, 'sortType');
if (sortType === 'asc') {
sortType = 'desc';
cell.innerHTML += '▼';
} else{
sortType = 'asc';
cell.innerHTML += '▲';
}
jQuery.data( cell, 'sortType', sortType);
var cellIndex = cell.cellIndex;
var chkSort = true;
while (chkSort){
chkSort = false;
$('table > tr').each(function(inx, row) {
if (inx===0 || !row.nextSibling) return;
var fCell = row.cells[cellIndex].innerHTML.toLowerCase();
var sCell = row.nextSibling.cells[cellIndex].innerHTML.toLowerCase();
if ( (sortType === 'asc' && fCell > sCell)
|| (sortType === 'desc' && fCell < sCell) ) {
$( row.nextSibling ).insertBefore( $(row) );
chkSort = true;
}
});
}
}
</script>
</head>
<body>
<div id='targetPn' style='width:130px'>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment