8

I dynamically add new row on DataTables 1.10.2 using the table.row.add() method using this code:

table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).draw();

I produced this mark-up:

<tr role="row" class="odd">
    <th>1 .</th>
    <td class="sorting_1">ID Fee</td>
    <td>All students</td>
    <td></td>
    <td>
        <button class="btn btn-null btn-xs" onclick="_remove(59, 'ID Fee')">
            <span class="fui-cross"></span>
        </button>
        <button class="btn btn-null btn-xs" onclick="_edit(59, 'ID Fee', '', '')">
            <span class="icon-pencil"></span>
        </button>
    </td>
</tr>

What I want to do is to add a data-id (and other data) attribute to the newly added tr tag (on or after row insert) and make it something like this:

<tr data-id="59" role="row" class="odd">

I've managed to get the index of the newly added row using the code and it returns the last row index:

var i = table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).index();

And also tried to perform the following to add the data-id attribute using that index:

var id = $("#department_id").val();
table.row(i).attr("data-id", id);
// table.row(i).data("id", id);
// I wanted to try this but there is also a method called data() already in
// DataTables so it will not work like in JQuery.

I'm new to DataTables and already scrolled its sourcecode, red the comments. Though not good at understanding its functions that begins with _fn*(). If there's any other way without relying on these _fn*() functions, thanks!

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Gideon
  • 1,469
  • 2
  • 26
  • 57
  • in your commented code, you say you wanted to do something like `table.row(i).data("id",id);` but cannot since DataTables has a function `data`. Have you tried wrapping `table.row(i)` in a jQuery function then calling jQuery's `data` on that? – Blundering Philosopher Nov 07 '14 at 17:20
  • 2
    `table.row(i)` is not a jquery object. You can't expect the data or attr functions to work with it. You'd need to wrap it first in the jQuery function before you can use the other functions `$(table.row(i)).data("id", id);` – evolutionxbox Apr 15 '15 at 16:37
  • Did you ever solved this, or it is still an open issue? – davidkonrad Apr 25 '15 at 16:33
  • I havent yet solved this. :-( – Gideon May 02 '15 at 07:18

1 Answers1

12

You can use rows().nodes() API function, see below:

var i = table.row.add([
    '',
    name,
    target_l,
    details,
    panel.html()    
]).index();

var id = $("#department_id").val();
table.rows(i).nodes().to$().attr("data-id", id);
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185