I have a jQuery DataTable that I'd like to add html tr rows to. These rows come in the form of a html string. I can add these to the table using standard jQuery, but this means they bypass the DataTable object and are lost when the table is resorted. To use the DataTable rows.add() function would mean I'd need the rows in array format.
// table_rows actually comes from an ajax call.
var table_rows = '<tr>...</tr><tr>...</tr><tr>...</tr>';
// This successfully adds the rows to the table... :-)
$('#datatable_id').append(table_rows);
// ...but those rows are lost when we redraw the DataTable. :-(
table = $("#datatable_id").DataTable();
table.order([0,'desc']).draw();
Unfortunately I can't easilly change what comes back from the server, so it seems I need a client side solution.
You should not manipulate the table directly and use appropriate jQuery DataTables API methods.
You can use rows.add()
API method to add multiple rows while supplying tr
nodes. You can construct tr
nodes from your server response.
For example:
var table_rows = '<tr><td>Tiger Nixon</td><td>System Architect</td><td>Edinburgh</td><td>61</td><td>2011/04/25</td><td>$320,800</td></tr>';
table.rows.add($(table_rows)).draw();
See this jsFiddle for code and demonstration.
If you are adding multiple tr
like below.
var table_rows = ' <tr><td>Tiger Nixon</td><td>System Architect</td><td>Edinburgh</td><td>61</td><td>2011/04/25</td><td>$320,800</td></tr> \r\n<tr><td>Tiger Nixon</td><td>System Architect</td><td>Edinburgh</td><td>61</td><td>2011/04/25</td><td>$320,800</td></tr>';
In the above string there are spaces between </tr>
and <tr>
tag and \r\n
.
you need to remove those spaces and \r\n
tag.
obj = obj.replace(/^\s*|\s*$/g, '');
obj = obj.replace(/\\r\\n/gm, '');
var expr = "</tr>\\s*<tr";
var regEx = new RegExp(expr, "gm");
var newRows = obj.replace(regEx, "</tr><tr");
myDataTable.rows.add($(newRows)).draw();
Above code solved my problem.