randomnessrandomly
randomnessrandomly

Reputation: 135

Delete rows in Datatable before destroying

I am initializing a Datatable each time the function lds is called. The function lds pulls data for table and appends the relevant HTML by

$('#tablebody').html(data);

After that I am initializing a datatable like so,

$('#rTable').Datatable({
      paging:false,
      destroy: true
});

This solves the problem of the error "Datatables cannot be initialized" if I call the lds function again. But the old rows are retained that were appended previously. I have tried the following approaches:

Assigned var table to the initialization of Datatable and put table.empty() at the beginning of lds. But as expected, the table variable is undefined.

Tried to delete row(0) while length > 0 but that messes the table and deletes the as well.

Tried ('#rTable').empty() but due to this Datatables throws an error d[i] not defined.

What is an approach I can take to empty the rows each time the function lds is called.

Upvotes: 0

Views: 269

Answers (1)

Jishnu Sukumaran
Jishnu Sukumaran

Reputation: 46

Destroy an existing table on a button click

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

$('#tableDestroy').on( 'click', function () {
    table.destroy();
} );

Reload a full table description from the server, including columns:

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

$('#submit').on( 'click', function () {
    $.getJSON( 'newTable', null, function ( json ) {
        table.destroy();
        $('#myTable').empty(); // empty in case the columns change

        table = $('#myTable').DataTable( {
            columns: json.columns,
            data:    json.rows
        } );
    } );
} );

Upvotes: 1

Related Questions