dynamically draw the headers of the table
dynamically draw the headers of the table
hattricknz
Posts: 10Questions: 6Answers: 0
What I am trying to do is dynamically draw the column headers. I have got to a stage where I have read in the file and I have the column headers in an array like this
[ { data: 'DeviceName' },
{ data: 'counter1' },
{ data: 'counter2' },
{ data: 'counter3' },
{ data: 'counter4' } ]
So I f my understanding is correct, I have to change the values of the columns:
array to my new array. I am just not sure how to do this.
I also think I then have to draw the <th>
tags based on my new array
here is a snippet of my code:
oTable = $('#counterTableDomId').DataTable({
...
columns: [
{ data: 'DeviceName' },
{ data: 'counter1' },
{ data: 'counter2' },
{ data: 'counter3' },
{ data: 'counter4' }
],
...
});
Currently I have to hard code like below:
<table id="counterTableDomId" class="display">
<thead>
<tr>
<th>DeviceName</th><th>counter1</th><th>counter2</th><th>counter3</th><th>counter4</th>
</tr>
</thead>
</table>
This discussion has been closed.
Answers
I haven't tried it, but this post looks like it is doing what you want.
http://datatables.net/forums/discussion/29877/populating-column-names-from-ajax-source-dynamically#latest
(The search engine found that post very quickly.)
I think I am approaching this the wron way. I am looking at being able to dynamically draw the headers. So as I have been advised, I have to create a class that can be initiliised and then when I get the headers values I can the pass them into the class e.g. t1.addHeaders(ch) and then the headers will be drawn. see here for a similar question I posted.
I do something like this on all my tables.
I create a columns collection and add the individual columns to them
column = new column(options) based upon my class, I pass everything via optional parameters. Name, title, if visible, class, style, dataName, , everything
columns.add(myColumn)
If I'm creating new table, it send the table to the dom based upon the columns collection
Now I call an ajax routine to get the contents of the table (actually the ajaxSource is defined in the creation of the mytable class)
When I'm ready to output the table, I do something like this
mytable.json(columnName1, dataValue1)
mytable.json(columnName2, dataValue2)
mytable.json(columnName3, dataValue3)
Depending upon whether I'm creating a new table or updating an existing table. In the myTable class, I format either a json response (for new insert), or javascript for data() row update.
If you are only updating one table. Having a class top interface with dataTables is a lot or overhead, and not necessary.
If you have several tables or more, it's a blessing.