Last active
June 5, 2017 23:38
-
-
Save gujc71/0a6ed25fe8909e1a51707457634378f6 to your computer and use it in GitHub Desktop.
js sample for table sorting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> | |
/* | |
save sort infomation for each field | |
*/ | |
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>').attr('border', 1).attr('width', 200); | |
$('#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); | |
}); | |
}); | |
function sortTable(cell){ | |
var sortType = jQuery.data( cell, 'sortType'); | |
sortType = (sortType === 'asc') ? 'desc':'asc'; | |
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