Advertisement
Guest User

Untitled

a guest
Mar 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. function sortTable(n) {
  3.   var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  4.   table = document.getElementById("customers");
  5.   switching = true;
  6.   // Set the sorting direction to ascending:
  7.   dir = "asc";
  8.   /* Make a loop that will continue until
  9.   no switching has been done: */
  10.   while (switching) {
  11.     // Start by saying: no switching is done:
  12.     switching = false;
  13.     rows = table.getElementsByTagName("TR");
  14.     /* Loop through all table rows (except the
  15.     first, which contains table headers): */
  16.     for (i = 1; i < (rows.length - 1); i++) {
  17.       // Start by saying there should be no switching:
  18.       shouldSwitch = false;
  19.       /* Get the two elements you want to compare,
  20.       one from current row and one from the next: */
  21.       x = rows[i].getElementsByTagName("TD")[n];
  22.       y = rows[i + 1].getElementsByTagName("TD")[n];
  23.       /* Check if the two rows should switch place,
  24.       based on the direction, asc or desc: */
  25.       if (dir == "asc") {
  26.         if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
  27.           // If so, mark as a switch and break the loop:
  28.           shouldSwitch= true;
  29.           break;
  30.         }
  31.       } else if (dir == "desc") {
  32.         if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
  33.           // If so, mark as a switch and break the loop:
  34.           shouldSwitch= true;
  35.           break;
  36.         }
  37.       }
  38.     }
  39.     if (shouldSwitch) {
  40.       /* If a switch has been marked, make the switch
  41.       and mark that a switch has been done: */
  42.       rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  43.       switching = true;
  44.       // Each time a switch is done, increase this count by 1:
  45.       switchcount ++;
  46.     } else {
  47.       /* If no switching has been done AND the direction is "asc",
  48.       set the direction to "desc" and run the while loop again. */
  49.       if (switchcount == 0 && dir == "asc") {
  50.         dir = "desc";
  51.         switching = true;
  52.       }
  53.     }
  54.   }
  55. }
  56. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement