Search code examples
jquerydatatablescreate-tabledestroy

Destroy and recreate a jQuery Datatables


I have two jQuery datatables with server side processing. I have a checkbox where I hide and show the two tables. I would like to destroy the none displayed and create another table. How would I do this?

This is what I tried but ajax.reload does not fire.

if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})

Solution

  • as I see it you will never show 2 datatables in your page so why not use only one. you can initialize your datatable and use a sequence like this

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

    to recreate it as needed.