Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple rows to a jQuery DataTable from a html string

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.

like image 309
AntonChanning Avatar asked Feb 06 '26 05:02

AntonChanning


1 Answers

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.

like image 121
Gyrocode.com Avatar answered Feb 08 '26 21:02

Gyrocode.com