Reputation: 69
I'm having some trouble getting tablesorter to work with an HTML table that's being created with JQuery from JSON data. I get the table created, and the column headers highlight when I click them but it doesn't sort the data. The JQuery that creates the table is this:
function buildHtmlTable() {
var columns = addAllColumnHeaders(myList);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<thead/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1){
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
This builds the table, and has the THEAD and TBODY tags required by tablesorter. I then create the table and run the tablesorter function like this:
$(document).ready(function() {
buildHtmlTable();
$('#excelDataTable').tablesorter();
});
This is the HTML:
<body>
<table id="excelDataTable" class="tablesorter">
</table>
</body>
When I click on the table headers they get highlighted by a blue box (like they're aware of being clicked), but they do not sort. I thought it had something to do with created the table dynamically, as the tablesorter will work with a hardcoded HTML table. But for this application I will be getting JSON data and will need to build out the table based on what I receive. The table data will not change dynamically, its just created that way. Any help appreciated, and will definitely post back further details if needed. Thanks in advance!
Upvotes: 1
Views: 887
Reputation: 69
Mottie's suggestion to use the build widget worked for me. I changed the file format containing the data from JSON to CSV. Javascript is
$(function() {
$('#excelDataTable').tablesorter({
theme: 'blue',
widgets: ['zebra'],
widgetOptions: {
// *** build widget core ***
build_type : 'csv',
build_source : { url: 'data.txt', dataType: 'text' },
build_headers : {
widths : ['50%']
}
}
});
});
And HTML is simply
<body>
<div id="excelDataTable"></div>
</body>
Also, I did have to do some tweaking to get chrome to use a locally hosted file, however this worked straight away in IE.
Upvotes: 2