Dynamically assign column headers
Dynamically assign column headers

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:
I have a dataset, based on an Oracle query, where column names and counts might change.
Is there a way to create a jQuery datatable based on this changing dataset?
I don't want to manually add/remove/update column headers as query gets updated.
Dataset is result of a query like this:
select metric,
listagg(case when site_name = 'X' then TS end) X,
listagg(case when site_name = 'Y' then TS end) Y
from whatever;
With dataset looking like:
metric X Y
blah 1 4
And later it might have an added column:
select metric,
listagg(case when site_name = 'X' then TS end) X,
listagg(case when site_name = 'Y' then TS end) Y,
listagg(case when site_name = 'Z' then TS end) Z
from whatever;
resulting in:
metric X Y Z
blah 1 4 2
I know I can change column header if I know what it is, like:
$(document).ready(function () {
vat table = $('#example').DataTable()'
$('#example thead th:eq(0)').html('new column header');
}
Answers
Datatables doesn't support dynamically changing the number of columns. Using
destroy()
will allow for changing the number of columns. See the second example in the docs for one way to do this.The
columns.title
option will allow Datatables to build the header. You can start with just atable
tag and define your columns with -option columns.title`.Kevin
Thank you Kevin. I figured it out.
Once I got my dataset through an Ajax call, I used the following to setup columns,
Just a watered down version.
Yep, that looks good!
Kevin