The output of the asp.net datagrid doesn’t include the thead and tbody elements required for the jquery tablesorter to work.
E.g. it looks like this:
<table> <tr>this is my header row</tr> <tr>content row 1</tr> <tr>content row 2</tr> <tr>content row 3</tr> ... <tr>content row n</tr> </table>
and it needs to look like this:
<table> <thead> <tr>this is my header row</tr> </thead> <tbody> <tr>content row 1</tr> <tr>content row 2</tr> <tr>content row 3</tr> ... <tr>content row n</tr> </tbody> </table>
I knocked up the following javascript to dynamically insert them, but the table is still not sortable. I’ve confirmed that if I manually insert the thead and tbody tags directly into the output html, the table is sortable, but when I try to do it using the DOM, it doesn’t seem to work.
What am I missing?
$(document).ready(function() { var tbl = document.getElementById('mytableid'); // new header and body elements to be inserted var tblHead = document.createElement('thead'); var tblBody = document.createElement('tbody'); // get the first row and the remainder var headerRow = $(tbl).find('tr:first') var bodyRows = $(tbl).find('tr:not(:first)'); // remove the original rows headerRow.remove(); bodyRows.remove(); // add the rows to the header and body respectively $(tblHead).append(headerRow); $(tblBody).append(bodyRows); // add the head and body into the table $(tbl).append(tblHead); $(tbl).append(tblBody); // apply the tablesorter $(tbl).tablesorter(); } );
EDIT: I actually solved the problem before I posted the question, but I thought I’d go ahead and post it anyway, as it may be useful to others… See my answer below.
Apparently, a phantom <tbody> element appears in the output. The trick is to ensure that it is removed before adding in the generated ones… Hopefully this will be useful to someone!