JQuery / Javascript: client-side change of asp.net datagrid output to allow tablesorter to work

The asp.net datagrid output file does not include thead and tbody elements necessary for jquery tablesorter to work.

eg. 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 should 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 down the following javascript to insert them dynamically, but the table is still not sorting. I confirmed that if I manually insert thead and tbody tags directly into the html output, the table is sorted, but when I try to do it using the DOM, this does not 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 really solved the problem before I posted the question, but I thought that I would continue and post it anyway, as this might be useful to others ... See My answer below.

+4
source share
2 answers

Apparently, a phantom <tbody> element appears in the output. The trick is to remove it before adding it to the generated ... I hope this will be useful to someone!

  $(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(); // SOLUTION HERE: // remove any existing thead/tbody elements $(tbl).find('tbody').remove(); $(tbl).find('thead').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(); } ); 
+5
source

The above code still does not address the cells in the header. To convert them from tags to tags, you can add this:

$('thead tr td').each(function(i) { $(this).replaceWith("<th>" + $(this).html() + "<\/th>"); });

0
source

All Articles