0

I have to add a row to a jquery datatable dynamically. The problem is, that I have several cells with a data-sort attribute. How can I add that attributes to the added rows?

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Preis</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td data-sort="Max Müller">M. Müller</td>
            <td data-sort="500">5,00 €</td>
        </tr>
    </tbody>
</table>
table.row.add([
    'J. Wayne', // Here I need a data-sort="John Wayne"
    '6,00 €', // Here I need a data-sort="600"
]).draw();
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Dominik Barann
  • 675
  • 2
  • 10
  • 25
  • **[this](http://stackoverflow.com/questions/14286528/datatables-dynamically-add-row-with-fnadddata-or-similar-and-add-a-class-to-a-sp)** might be helpful. – mmushtaq Aug 02 '16 at 09:36

1 Answers1

1

A convenient way would be to use a createdRow callback that automatically populates all <td> values with a data-sort attribute containing the column content :

$('#example').DataTable({
  createdRow: function( row, data, dataIndex ) {
    data.forEach(function(str, idx) {
      $(row).find('td').eq(idx).attr('data-sort', str)
    })
  }
}) 

It is working here -> http://jsfiddle.net/ea5ayzzb/

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • Sounds good. Can I also add that callback after the initialization of the table like an event `table.on('draw.dt', myFunction);`? My table is created earlier. – Dominik Barann Aug 02 '16 at 12:42
  • @DominikBarann, I really dont get what you mean? You cannot add a callback once the table is created. but why would you do that? – davidkonrad Aug 03 '16 at 06:29
  • The problem is, that I have a class `.data-table`. Every table with that class becomes a datatable with some default options. Now there is that one table where I need that callback and I can't reinit it, because it has already been initialised. – Dominik Barann Aug 03 '16 at 07:31