CdSdw CdSdw - 5 months ago 28
Javascript Question

Sorttable.js (Javascript table sorting) not working when table created in javascript

I'm trying to use the sorttable.js package to make an HTML table sortable when the column header is clicked. I can get this to work just fine when the table is declared statically in the HTML:

fiddle

<table class="sortable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>Joe</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Abraham</td>
<td>Jones</td>
<td>4</td>
</tr>
</table>


However, when I create the table with javascript, the sorting functionality isn't there anymore, and I get error messages on the console:

fiddle

tbl_array = new Array()
tbl_array = [["Firstname","Lastname","Points"], ["Eve","Jackson","94"], ["Joe","Smith","50"], ["Abraham","Jones","4"]]
var body = document.body,
tbl = document.getElementById('summaryTable');

// clear all rows on the table
while(tbl.rows.length > 0){
tbl.deleteRow(0)
}
tbl.style.width = '100px';
tbl.style.border = '1px solid black';

numRows = tbl_array.length
numCols = tbl_array[0].length

// insert each 2D array entry into a table cell
for(var i = 0; i < numRows; i++){

// insert header
if (i == 0){
var header = tbl.createTBody();
var row = header.insertRow();
for (var j=0; j < numCols; ++j){
var cell = document.createElement('th')
cell.appendChild(document.createTextNode(tbl_array[i][j]));
cell.style.border='1px solid black';
cell.style.fontWeight = "bold";
row.appendChild(cell)
}
}

else{
var tr = tbl.insertRow();
for(var j = 0; j < numCols; j++){
var td = tr.insertCell();
td.appendChild(document.createTextNode(tbl_array[i][j]));
td.style.border = '1px solid black';
}
}
}
console.log("tbl", tbl)


The only thing I can think of is that I'm not formatting the table correctly with the javascript, but when I printed both tables to the console and examined their structures, they were basically the same:

<table ...>
<tbody>
<tr ...>
<th>..</th>
<th>..</th>
</tr>
<tr>
<td>..</td>
<td>..</td>
</tr>
</tbody>
</table>


Is my error in the way I'm creating the table with javascript? Any help would be appreciated. Thanks!

Answer

sorttable.js assumes all tables are already in the HTML when it initializes; your table is dynamically generated, so you have to bootstrap the makeSortable method manually.

Right before your console.log, try inserting this:

sorttable.makeSortable(document.getElementById('summaryTable'));