Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 698
Sebastien Avatar asked Jan 14 '14 13:01

Sebastien


Video Answer


2 Answers

Here is a more cleaner approach that I found here:

table.row.add( [ ... ] ).node().id = 'myId';
table.draw( false );
like image 95
Sammie Avatar answered Sep 27 '22 21:09

Sammie


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'
]);
like image 29
dcodesmith Avatar answered Sep 27 '22 21:09

dcodesmith