Sebastien
Sebastien

Reputation: 250

jQuery dataTables add id to added row

Is it possible to add ID to last added row with jQuery DataTables (e.g., <tr id="myid">...</tr>) ?

$('#example').dataTable().fnAddData( [
        "col_value_1",
        "col_value_2",
        "col_value_3",
        "col_value_4" ] );

(Add id to this new row)

Upvotes: 15

Views: 35839

Answers (6)

samuelabate
samuelabate

Reputation: 1631

Here is a more cleaner approach that I found here:

table.row.add( [ ... ] ).node().id = 'myId';
table.draw( false );

Upvotes: 9

YakovGdl35
YakovGdl35

Reputation: 349

This worked for me

var rowNode=$('#MyTable').DataTable().row.add([1,2,3]).draw( false );

rowNode.id='myId';

rowNode.id='myId';

Upvotes: 1

dcodesmith
dcodesmith

Reputation: 9614

Use the fnCreatedRow/createdRow Callback. It is best to set the id attribute of the table row on creation of the row. Use what the API has provided and you won't need to hack it or have messy code

This function is called when a TR element is created (and all TD child elements have been inserted), or registered if using a DOM source, allowing manipulation of the TR element (adding classes etc).

//initialiase dataTable and set config options
var table = $('#example').dataTable({
    ....
    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'my' + iDataIndex); // or whatever you choose to set as the id
    },
    ....
});

// add data to table post-initialisation
table.fnAddData([
    'col_value_1',
    'col_value_2',
    'col_value_3',
    'col_value_4'
]);

Upvotes: 30

RogerMKE
RogerMKE

Reputation: 737

If you use row.add() it is easy to set the id:

   var table = $('#example').DataTable();
   var rowNode = table.row.add([
        "col_value_1",
        "col_value_2",
        "col_value_3",
        "col_value_4"
    ]).node();

    $(rowNode).attr("id", myid);

The .node() returns the element of the newly added row.

Upvotes: 4

Rolwin Crasta
Rolwin Crasta

Reputation: 4349

This worked for me

var MyUniqueID = "tr123"; // this is the uniqueId.
var rowIndex = $('#MyDataTable').dataTable().fnAddData([ "column1Data", "column2Data"]);
var row = $('#MyDataTable').dataTable().fnGetNodes(rowIndex);
$(row).attr('id', MyUniqueID);

Upvotes: 8

Pragnesh Khalas
Pragnesh Khalas

Reputation: 2898

Hope below code will help you

var rowid = $('#example').dataTable().fnAddData( [
    "col_value_1",
    "col_value_2",
    "col_value_3",
    "col_value_4" ] );
var theNode = $('#example').dataTable().fnSettings().aoData[rowid[0]].nTr;
theNode.setAttribute('id','your value');

Upvotes: -1

Related Questions