toothful
toothful

Reputation: 892

Search does not work for dynamically created rows

I'm using jQuery Datatables and I have a HTML page where I am displaying records from database in a table. Initially the table is loaded with 50 records and then I am appending 50 records each time it scrolls to bottom.

Now, jQuery DataTables search function works fine for first 50 records but it can not recognize the other records which are dynamically created during infinite scroll.

HTML and DataTables initialization:

$(document).ready( function() {
   $('body #new_table').dataTable( {
    'scrollX': true,
    'scrollY': 600,
    'paging':   false,
    "ordering": false,
    'info' : false,
    'aaSorting': []

 });
});
<table id="new_table">
  <thead>
    <tr>
      <th>ChemicalID</th>
      <th>Product</th>
      <th>Manufacturer</th>
      <th>Registered Name</th>
    </tr>
  </thead>
  <tbody id="items" class="display table table-bordered">
    @foreach($data as $chemical)
    <tr class="item">
      <td>{{$chemical->ChemicalID}}</td>
      <td>{{$chemical->Product}}</td>
      <td>{{$chemical->Manufacturer}}</td>
      <td>{{$chemical->RegisteredName}}</td>
    </tr>
    @endforeach
  </tbody>
</table>

Upvotes: 3

Views: 3008

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

CAUSE

If you're just appending tr nodes to the table, search will not find those rows as jQuery DataTables is not aware of them.

SOLUTION

Use row.add() or rows.add() API methods to add new rows, only then new rows would be visible to jQuery DataTables.

For example, to add a new row to the table and redraw:

var table = $('#example').DataTable();

table.row.add([
    "Tiger Nixon",
    "System Architect",
    "Edinburgh",
    "61",
    "2011/04/25",
    "$320,800"
]).draw(false);

See this jsFiddle for demonstration.

To add a new row to the table using tr node and redraw:

var table = $('#example').DataTable();

table.row.add($(
    '<tr>' +
    '<td>Tiger Nixon</td>' +
    '<td>System Architect</td>' +
    '<td>Edinburgh</td>' +
    '<td>61</td>' +
    '<td>2011/04/25</td>' +
    '<td>$320,800</td>' +
    '</tr>'
)).draw(false);

See this jsFiddle for demonstration.

Upvotes: 5

Related Questions