4

I have a existing datatable in my html page, and I try adding new row using fnAddData

var addId = vandropDatatable.fnAddData(["1", "2"]);

How can I findout the new added row to add some class for it (for example addClass("New_item") )

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
VinhNT
  • 1,091
  • 8
  • 13

3 Answers3

7

Updated in order to reflect dataTables 1.10.x. The original answer below was targeting 1.9.x. It is still applicable but the 1.10.x API way is more powerfull :

$("#add").click(function() {
    var row = table.row.add([
        'new',
        'new',
        'new',
        'new',
        'new'
    ]).draw();
    row.nodes().to$().addClass('newRow');
});

1.10.x demo -> http://jsfiddle.net/0scq8rkm/

In 1.10.x you get an API object back, holding the row. nodes().to$() let you work on the internal row node as it was a jQuery object.


Lets say you want to give new <tr>'s the following layout :

tr.newRow {
    background-color: red;
    font-size: 20px;
}

and you have an add button :

<button id="add">add new row</button>

now, when clicking on the add button, use the returned rowindex for the newly created <tr> to get the right row through the function fnGetNodes :

$("#add").click(function() {
    var rowIndex = dataTable.fnAddData([
        'new',
        'new',
        'new',
        'new',
        'new'
    ]);
    var row = dataTable.fnGetNodes(rowIndex);
    $(row).removeClass().addClass('newRow');
});

see fiddle -> http://jsfiddle.net/q4E3Y/

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
0

Try changing your fnRowCallback to the following:

"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
  nRow.className = "your new class";
  return nRow;
}

http://datatables.net/examples/advanced_init/row_callback.html

Bhupendra Shukla
  • 3,814
  • 6
  • 39
  • 62
  • 1
    I just wanna add new class for onerow, my situation here is 1. Render the table completed, add a "Add new Button" 2. After addnew button clicked, add new row to existing dataable and highlight that new added row. If do it in the call back like this way, all the row has the same class, so, no row will be highlighted – VinhNT Mar 12 '14 at 07:34
0

What worked for me was to add the new row, draw and then get the newly added row using node().

$("#add").click(function() {
    var newRow = table.row.add([
        'new',
        'new',
        'new',
        'new',
        'new'
    ]).draw().node();
    $(newRow).addClass('newRow');
});

This follows the same process that's listed in the documentation.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82