Search code examples
javascriptdatatabledestroy

Datatables table data clearing and table destroying not giving a result


I'm using DataTables with Aurelia framework. Table and it's sorting works well, excluding one moment. When I retrieving a new data table should be cleared and redrawn with new data, but I always see rows with data which have been passed before and now.

My ini code:

if (this.results && this.results.length > 0) {

    console.log('resultsChanged');

    setTimeout(() => {
        this.table = $('#searchResultsTable').DataTable({
            retrieve: true,
            searching: false,
            paging: false,
            info: false,
            orderMulti: false,
            order: [[2, "asc"]],
            dateFormat: 'dd.mm.YYYY'
        });
    }, 200);
}

I have tried to use 'destroy: true' as option, but it restores the first data source, doesn't clear table.

Also I have tried to use this before if condition:

if ($.fn.DataTable.isDataTable('#searchResultsTable')) {
    console.log('table exists')
    $.fn.dataTable.destroy('#searchResultsTable');
    // $('#searchResultsTable').dataTable.fnDestroy();
}

But $.fn.dataTable.destroy('#searchResultsTable'); always throws an error $.fn.dataTable.destroy is not a function.

Looking for you advices and help.

UPDATE(full fucntion):

resultsChanged(): void {

    let timeout = 200;

    if ($.fn.DataTable.isDataTable('#searchResultsTable')) {
        console.log('table exists')
        this.table.destroy('#searchResultsTable');
        timeout = 0;
    }

    if (this.results && this.results.length > 0) {

        console.log('resultsChanged');

        setTimeout(() => {
            this.table = $('#searchResultsTable').DataTable({
                retrieve: true,
                searching: false,
                paging: false,
                info: false,
                orderMulti: false,
                order: [[2, "asc"]],
                dateFormat: 'dd.mm.YYYY'
            });
        }, timeout);
    }
}

Solution

  • If you want to clear data-table and re-draw it again you can do it with destroy() method and re-initialize the data-table which is the approach that you took also.

    $.fn.dataTable.destroy('#searchResultsTable'); // This will not work
    

    The above code didn't work because according to the documentation there is no such a method.

    So what you can do is use destroy() like this.table.destroy(). Note that destroy() method accepts optional Boolean parameter, which by default is false, meaning that the table will be restored to it's initial state(so later we can re-initialize it). If you pass true the table will be completely removed from the DOM

    A sample code snippet:

    $(document).ready(function() {
      var table,
          btnDestroy = $('#destroy'),
          btnReInit = $('#init'),
          btnRand = $('#random');
    
      init();
    
      btnDestroy.on('click', destroy);
      btnReInit.on('click', init);
      btnRand.on('click', randomData);
    
      function destroy() {
        try {
          table.destroy();
          btnDestroy.attr('disabled', true);
          btnReInit.attr('disabled', false);
          btnRand.attr('disabled', false);
        } catch (e) {console.log(e.message);}
      }
    
      function init() {
    
        table = $('#my-data-table').DataTable({
          retrieve: true,
          searching: false,
          paging: false,
          info: false,
          orderMulti: false,
          order: [
            [0, "asc"]
          ]
        });
        btnDestroy.attr('disabled', false);
        btnReInit.attr('disabled', true);
        btnRand.attr('disabled', true);
      }
    
      function randomData() {
        var tbody = $('#my-data-table tbody');
        tbody.html('');
        var rows = [];
        var iterations = Math.floor(Math.random() * 5) + 3; // Random count rows
        for (var i = 0; i < iterations; i++) {
          rows.push('<tr><td>' + i + '</td><td>user ' + i + '</td><td>' + Math.floor(Math.random() * 10000) + 100 + '</td></tr>');
        }
    
        tbody.html(rows.join(''));
      }
    });
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    
    <p>You can randomize the data before Re-Initialize</p>
    <button type="button" id="destroy">Destroy</button>
    <button type="button" id="init" disabled>Re-Initialize</button>
    <button type="button" id="random" disabled>Random Data</button>
    
    <table id="my-data-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>User</th>
          <th>Value</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>user 1</td>
          <td>34569</td>
        </tr>
        <tr>
          <td>2</td>
          <td>user 2</td>
          <td>137</td>
        </tr>
      </tbody>
    </table>