I am trying to use the jQuery plugin tablesorter (tablesorter.com) on an html table that is generated by a javascript array when my page loads. The table gets styled, by the table won't sort when the column headers are clicked.
Here is what I have so far:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/lib/jquery-ui/jquery-ui-1.11.4/external/jquery/jquery.js"></script>
<script type="text/javascript" src="/lib/jquery-ui/jquery-ui-1.11.4/jquery-ui.js"></script>
<link type="text/css" rel="stylesheet" href="/lib/jquery-ui/jquery-ui-1.11.4/jquery-ui.css">
<script type="text/javascript" src="/lib/jquery/tablesorter/jquery.tablesorter.js"></script>
<link type="text/css" rel="stylesheet" href="/lib/jquery/tablesorter/themes/blue/style.css">
<style>
</style>
<script>
$( document ).ready( function() {
$( "table" ).tablesorter();
$( "p" ).click( function() {
$( this ).hide();
});
});
$( function() {
$( "#datepicker" ).datepicker();
});
</script>
<script>
var frameData = [
["Phoenix Smasher", 15],
["Bone Breaker", 16],
["DeathFist", 60],
["Thruster", 20],
["S Jab", 10]
];
function pageLoad() {
var t = "";
t += "<thead>";
t += "<tr>";
t += "<th>Move</th>";
t += "<th>Start Up</th>";
t += "</tr>";
t += "</thead>";
t += "<tbody>";
for (var i = 0; i < frameData.length; i++) {
t += "<tr>";
t += "<td>" + frameData[i][0] + "</td><td>" + frameData[i][1] + "</td>";
t += "</tr>";
}
t += "</tbody>";
document.getElementById("frameTable").innerHTML = t;
}
</script>
</head>
<body onload="pageLoad()">
<p>Click the table headers to sort the array in descending order.</p>
<br />
<br />
<div id="demo"></div>
<table id="frameTable" class="tablesorter">
</table>
<p>jQuery test. This text will disappear on click.</p>
<input type="text" id="datepicker">
</body>
</html>
What I've tried: Oddly enough, when I get rid of the javascript array and place actual html table data in between the <table>
and </table>
tags, the tablesorter plugin works fine. Also, I've tried re-arranging the array and pageLoad()
function with the jQuery code, with no luck at all.
Any idea how to get this to work?
The page is on my server: http://sketchcarellz.com/multiArray.html
Your issue is you are initializing the plugin before the table is built.
Switch the order of execution. To do this only use one load handler to be assured you know the sequencing
$( document ).ready( function() {
pageload();
// table is build, call plugin
$( "table" ).tablesorter();
});