How do I set the default attributes for my cells when there is no initial data

Viewed 17

I have a scenario where I am filling my data table based on data received over a websocket. So I guess the best approach would be to create an empty table in html and then add the data via the API.

So say I want my final table to appear something like:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="name">Tiger Nixon</td>
            <td class="position">System Architect</td>
            <td class="office">Edinburgh</td>
            <td class="age">61</td>
            <td class="start-date">2011/04/25</td>
            <td class="salary">$320,800</td>
        </tr>
        <tr>
            <td class="name">Garrett Winters</td>
            <td class="position">Accountant</td>
            <td class="office">Tokyo</td>
            <td class="age">63</td>
            <td class="start-date">2011/07/25</td>
            <td class="salary">$170,750</td>
        </tr>
    </tbody>
</table>

When dynamically loading my table I would only define the first part:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
</table>

And then call row.add() in my javascript as the data is received.

But how do I set the default classes for my column cells this way?

1 Answers

When you use row.add(), the return value is the newly created (but not yet displayed) row.

You can use this value to iterate over the cells in the row, where class names can be added. Finally you can draw the row, so it is displayed.

The following shows the basic approach, where we have a pre-defined array of the class names you want to handle:

  $(document).ready(function() {
  
    var classNames = [ 'name', 'position' ];
 
    var table = $('#example').DataTable();
    
    var row = table.row.add( ['Quinn Flynn', 'Accountant'] );
    var i = 0;
    row.cells().every( function () {
    var node = this.node();
      $( node ).addClass( classNames[i++] );
    } );
    row.draw();

  });

That final section of code from row creation to the row draw would be placed in a function, in your case.

This produces an HTML body as follows:

<tbody>
    <tr role="row" class="odd">
        <td class="name sorting_1">Quinn Flynn</td>
        <td class="position">Accountant</td>
    </tr>
</tbody>
Related