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({})
function destroy( [ remove ] ) When set to true , as of v1. 10.8, DataTables will use the jQuery . remove() method to remove the table from the page - this results in any events that are bound to the table elements being automatically removed by jQuery.
isDataTable() could be used, but this only works for table selectors, not for variables containing an initialized DataTable. This function is returning false for such variables: var table = $("#table"). DataTable(); // Valid initialized DataTable console.
In my case, to reset the table I just do this:
$('#table_id').DataTable().clear().destroy();
$('#table_id').empty();
With that you'll reset the table back to it's initial state and you may reinitialize it after that.
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.
You have to clear the div content for properly destroy
if($('#mode').is(':checked')) {
Table2 = $('#timesheet-table-2').DataTable({})
Table1.clear();
Table1.destroy();
$('#timesheet-table').empty();
}
else {
Table1 = $('#timesheet-table').DataTable({})
Table2.clear();
Table2.destroy();
$('#timesheet-table-2').empty();
}
You could try something like this (Here is a fiddle that might help):
function loadDataTable(type) {
$('#dataTableDiv').empty();
$('#dataTableDiv').append('<table cellpadding="0" cellspacing="0" border="0" class="dataTable table table-striped" id="example"> </table>');
var table1_columnList = [{
"data": "otherId",
"title": "Other ID"
}, {
"data": "firstName",
"title": "First Name"
}, {
"data": "lastName",
"title": "Last Name"
}, {
"data": "gender",
"title": "Gender"
}];
var table2_columnList = [{
"data": "id",
"title": "ID"
}, {
"data": "firstName",
"title": "First Name"
}, {
"data": "lastName",
"title": "Last Name"
}, {
"data": "gender",
"title": "Gender"
}, {
"data": "dob",
"title": "DOB"
}, {
"data": "race",
"title": "Race"
}];
var columnList = "";
if (type == 'table1')
columnList = table1_columnList;
else
columnList = table2_columnList;
myTable = $('#example').DataTable({
"sPaginationType": "full_numbers",
data: datavar,
columns: columnList,
responsive: true,
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With