0

I have a HTML table with empty tbody, which gets populated in jquery function on selecting some filters(typically select options). The DataTable is used for pagination if the table elements exceeds the limit.

When the filter is applied for the first time, it works fine. But when the table contents are updated by jquery, DataTable doesn't seem to update it with new data.

HTML looks like:

<table class="table table-striped table-hover outline" id="result" >
    <thead>
       <tr>
           <th>Name</th>
           <th>ID</th>
           <th>Age</th>        
           <th>Department</th>  
       </tr>
    </thead>
    <tbody>
    </tbody>
</table>

And the Jquery function:

$(document).ready(function(){

    function filterData(list) {

        /*filter and send updated list*/

        return list;
    }

    /* some other code */
    data = filterData(rawData); //Function will filter the data

    var html = ''; //html part to be appended in the results table

    data.forEach(function(d) {
        html += '<tr>'; //create a table row
        for (var key in d) 
            html += '<td>'+ d[key] +'</td>';   //put all elements in the columns
        html += '</tr>';     
    });

    $("#result tbody").html(html); //display the result in table body

    $('#result').DataTable({
        scrollY:"300px",
        lengthMenu: [10,15,20]
    });

});

Any possible way to update the DataTable with new contents? Thanks in advance!

Yajnesh Rai
  • 290
  • 1
  • 6
  • 17

2 Answers2

0

You can use standard DataTable API's to add row dynamically.

var myDatatable = $('#result').DataTable({
        scrollY:"300px",
        lengthMenu: [10,15,20]
    });


data.forEach(function(d) {
     var html += '<tr>'; //create a table row
        for (var key in d) 
            html += '<td>'+ d[key] +'</td>';   //put all elements in the columns
        html += '</tr>';     

       // add row using standard API's and draw the table again
       myDatatable.row.add(html).draw();

    });
ScanQR
  • 3,740
  • 1
  • 13
  • 30
0

You need to use the following functionalities in datatable to update the table.

datatable.rows.add(newDataArray);
datatable.draw();
vineeth sivan
  • 510
  • 3
  • 18