Last active
June 7, 2017 10:46
-
-
Save gujc71/c06a1245f826bfcad153662bfa5cf5af 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> | |
/* | |
sort by each field (td click) | |
*/ | |
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)); | |
}); | |
if (inx===0){ | |
tr.find('td').click(function() { | |
sortTable(this.cellIndex) | |
}); | |
} | |
}); | |
}); | |
var sortType = 'asc'; | |
function sortTable(cellIndex){ | |
sortType = (sortType === 'asc') ? 'desc':'asc'; | |
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