Dynamic Columns Problem
Dynamic Columns Problem
I have a request where the datatable columns depend on the value of a select field.
Initially the datatable has 17 columns. When I select another option from the select it should have 11 columns.
The problem is that it displays 17 (the 11 new ones, plus 6 from before)
I redefine the columns and I destroy the datatable. Please advice.
Here is my code:
var column_titles = [];
//Add Table Columns
for(var i = 0; i < columns.length; i++) {
column_titles.push({ sTitle: columns[i].column_name, data: columns[i].column_name });
}
data_table = table.DataTable({
destroy: true,
serverSide: true,
processing: true,
ajax: {
"url" : some_url,
"type" : "POST",
"data": { "module": $("#mytforg_records_filter #module").val() }
},
columns: column_titles
});
Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.
This question has an accepted answers - jump to answer
Answers
You need to remove the HTML from the old table. I'd suggest calling
destroy()
with the option for it to remove the HTML (checking if the table exists before calling it of course).Alternatively call
destroy()
and then remove or add the columns from the DOM as you need.Allan
Hi Allan,
First of all thanks for the fast response.
I thought that setting destroy to true has the same effect.
Anyway the solution works perfectly.
Thanks
The problem with using
destroy
is that it will just destroy the old table, leaving it in the DOM and then immediately init a new table. You have no chance to do something in the middle (which you need to in this case - namely emptying the HTML).Good to hear you've got it working now.
Allan