user2770808
user2770808

Reputation: 347

Cant sort html table using sorttable.js

Im having trouble trying to sort a dynamically created html table. I create it using jade/pug. I am trying to use the sorttable.js script found here http://www.kryogenix.org/code/browser/sorttable/ . I am still kind of new to html/javascript. So if there is some obvious reason why its not working could someone point it out please?

Here is some of the html code generated from the template

<html>
  <head>
   <script src="/path/to/sorttable.js"></script>
   <style>
    th.clickable:hover
    {
     color:green
    }    
    th, td
    {
     padding:5px;
    }
    th.clickable
    {
     cursor: pointer;    
    }
  </style>
 </head>
 <body>
 <script>
  var newTableObject = document.getElementById(tbl)
  sorttable.makeSortable(newTableObject)
 </script>
 <table class="sortable" id="tbl">
  <tr>
   <th class="clickable">id</th>
   <th class="clickable">value</th>
  </tr>
  <tr>
  <td>100</td>
  <td>100</td>
 </tr>
  <tr>
  <td>200</td>
  <td>200</td>
 </tr> 
</table>
</body>
</html>   

The goal is to have it so when I click on the header it sorts the table by that column.

Upvotes: 0

Views: 1592

Answers (2)

brad
brad

Reputation: 1023

Please excuse if this is already known...but The script tag gets read and executed whenever the browser comes across it. Have you tried putting the script tag after your table?

Upvotes: 1

jusopi
jusopi

Reputation: 6813

At the time your code executes:

var newTableObject = document.getElementById(tbl)
sorttable.makeSortable(newTableObject)

Your table hasn't rendered yet and is unavailable. So you;re passing undefined to the sorttable.makeSortable method. You can test this by adding a trace statement after you get the element:

var newTableObject = document.getElementById(tbl)
console.log(newTableObject)

You should wait to fire this code after your table has rendered. Something like this:

onLoad = function(){
    var newTableObject = document.getElementById(tbl)
    sorttable.makeSortable(newTableObject)
}

and declare that like so:

// using jQ
$(document).ready( onLoad())

or for plain JS

<body onload="onload()">

Upvotes: 0

Related Questions