put data attribute on row add on DataTables 1.10
Asked Answered
B

1

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!

Bushranger answered 5/11, 2014 at 4:1 Comment(4)
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?Gosselin
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);Ganley
Did you ever solved this, or it is still an open issue?Hayrack
I havent yet solved this. :-(Bushranger
P
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);
Personality answered 1/5, 2015 at 5:21 Comment(3)
Not sure why, but .to$() is not working on .node() for me. Had to use $( table.row(i).node() )Delhi
@FelipeLeão, thanks for you comment. It appears that to$() only works with nodes() and not node() which is kind of undocumented. Your workaround is fine.Personality
.to$() turns the node into a jQuery element.Supramolecular

© 2022 - 2024 — McMap. All rights reserved.