views:

177

answers:

1

Hi

I am using the DataTable.net plugin and I am wondering how can I add dynamically a row to a existing table?

http://datatables.net/examples/api/add_row.html

I am looking at this example and they have it like this

/* Global variable for the DataTables object */
var oTable;

/* Global var for counter */
var giCount = 2;

$(document).ready(function() {
    oTable = $('#example').dataTable();
} );

function fnClickAddRow() {
    oTable.fnAddData( [
        giCount+".1",
        giCount+".2",
        giCount+".3",
        giCount+".4" ] );

    giCount++;
}

but I am wondering what happens if I want I have a table row already rendered?

Say this is my table.

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table> 

Now I have this

var newRow = '<tr><td>row 3, cell 1</td><td>row 3, cell 2</td></tr>';

How can I add it through addRow?

I tried oTable.fnAddData(newRow); but that seems not to work.

So I am not sure how to do this.

A: 

Call the fnAddData with an array of the values you want to add, like this:

oTable.fnAddData(["row 3, cell 1", "row 3, cell 2"]);

You can read more details from the API here, here's the arguments it takes:

  1. array strings : The data to be added to the table. This array must be of the same length as the number of columns on the original HTML table.
    or
    array array strings : 2D array of data to be added to the table. The inner array must be of the same length as the number of columns on the original HTML table.
  2. boolean : optional - redraw the table or not after adding the new data (default true)
Nick Craver
So I can't just add a rendered html string into it?
chobo2
@chobo2 - Not if you want it on the datatable, it's based on an object structure, you can [`.append()`](http://api.jquery.com/append/) to the table, but that won't do what you're after I don't think.
Nick Craver
Hmm. That sucks. Another problem I see. Is each of my table rows has a inline style. How would I stick that on it?
chobo2
@chobo2 - Inline styling is usually lost when you sort, etc anyway, can you give an example of the inline styling your after? (Any reason this can't be a class? There are many [class options available](http://datatables.net/styling/custom_classes)).
Nick Craver
Hi. When I render the table for the first all the inline styling does not seem to get lost. the reason why I don't use a class is each row has a unquie background color and font color set by the user. I am sure with some programming I could some how make it into classes but it would take time I don't have.
chobo2
Another problem is. Each of my td's have there own class attached to it. How do I add those as well?
chobo2