Skip to content

Instantly share code, notes, and snippets.

@leggetter
Created February 5, 2011 13:46
Show Gist options
  • Save leggetter/812463 to your computer and use it in GitHub Desktop.
Save leggetter/812463 to your computer and use it in GitHub Desktop.
Dynamically sorting a table with jQuery tablesorter plugin
<html>
<head>
<title>
jQuery v1.4.2 and jQuery tablesorter plugin sorting problem
</title>
</head>
<body>
<button id="add">Add Row</button>
<table class="tablesorter">
<thead>
<tr>
<th>Row</th>
<th>Name</th>
<th>Path</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Real-Time Twitter updates</td>
<td>/kwwika/twitter/hashtags/realtime</td>
<td>Topic</td>
</tr>
<tr>
<td>1</td>
<td>Kwwika Twitter updates</td>
<td>/kwwika/twitter/hashtags/kwwika</td>
<td>Topic</td>
</tr>
</tbody>
</table>
<link href="http://tablesorter.com/themes/blue/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script src="http://tablesorter.com/jquery.tablesorter.js"></script>
<script>
jQuery(function()
{
var table = jQuery(".tablesorter");
table.tablesorter();
jQuery("#add").click(function()
{
// Create random data and add to table
var name = createRandomName();
var topic = name.replace(/\s+/g, "-").toLowerCase();
var html = "<tr>" +
"<td>" + table.find("tbody tr").size() + "</td>" +
"<td>" + name + "</td>" +
"<td>/kwwika/test/" + topic + "</td>" +
"<td>topic</td>" +
"</tr>";
table.find("tbody").append(html);
// update table and sort
table.trigger("update");
setTimeout(function()
{
var sorting = [[1,0]];
table.trigger("sorton", [sorting]);
}, 0);
});
function createRandomName()
{
var startMillis = new Date(1900,0,1).getTime();
var endMillis = new Date(2100,0,1).getTime();
var randomDate = new Date(startMillis + Math.random()*(endMillis-startMillis));
var name = randomDate.toString().replace(/[^-_a-zA-Z0-9\ ]/g, "");
return name;
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment