Sort Columns from Tables


/ Published in: JavaScript
Save to your folder(s)

Use to sort table columns by clicking on the table headings


Copy this code and paste it in your HTML
  1. <table width='100%' id='tblNotifications' style='display: none;' class='TFtable'><thead id='notitblhead'>
  2. <tr>
  3. <th id='thDate' onclick='sortNotifications(this);' title='Click to sort by Date' style='width: 100px;'>Date</th>
  4. <th id='thType' onclick='sortNotifications(this);' title='Click to sort by Type'>Type</th>
  5. <th id='thDoc' onclick='sortNotifications(this);' title='Click to sort by Document Type'>Doc Type</th>
  6. <th id='thStatus' onclick='sortNotifications(this);' title='Click to sort by Status'>Status</th>
  7. <th id='thProcess' onclick='sortNotifications(this);' title='Click to sort by Process'>Process</th>
  8. <th style='width: 50px;'>Edit</th>
  9. </tr>
  10. </thead>
  11. <tbody id='notifications'>
  12. </tbody>
  13. <tfoot></tfoot>
  14. </table>
  15.  
  16. //javascript
  17.  
  18. var notinum = 1;
  19.  
  20. function sortNotifications(ele) {
  21. notinum *= -1;
  22. var sibling = prevAll(ele);
  23. var n = sibling.length;
  24. var fldtype = (ele.id == 'thDate') ? 'd' : ''; //use this line if a column is a date field where the year part is not the start of the string
  25. sortTableRows(notinum,n, fldtype);
  26. }
  27.  
  28. function prevAll(element) {
  29. var result = [];
  30.  
  31. while (element = element.previousElementSibling)
  32. result.push(element);
  33. return result;
  34. }
  35.  
  36. function sortTableRows(f,n, fld=''){
  37. var rows = $('#tblNotifications tbody tr').get();
  38.  
  39. rows.sort(function(a, b) {
  40.  
  41. var A = getVal(a, fld);
  42. var B = getVal(b, fld);
  43.  
  44. if(A < B) {
  45. return -1*f;
  46. }
  47. if(A > B) {
  48. return 1*f;
  49. }
  50. return 0;
  51. });
  52.  
  53. function getVal(elm,fld=''){
  54. var v = $(elm).children('td').eq(n).text().toUpperCase();
  55. if(fld !=''){
  56. v = getDateSortVal(v);
  57. }
  58. if($.isNumeric(v)){
  59. v = parseInt(v,10);
  60. }
  61. return v;
  62. }
  63.  
  64. function getDateSortVal(str){
  65. var sortdate = str.split("/");
  66. return sortdate[2]+'/'+sortdate[0]+'/'+sortdate[1];
  67. }
  68.  
  69. $.each(rows, function(index, row) {
  70. $('#tblNotifications').children('tbody').append(row);
  71. });
  72. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.