How to create colspan on header with ajax loaded data
How to create colspan on header with ajax loaded data

I'm trying to create colspan headers like the one shown in this example https://datatables.net/examples/basic_init/complex_header.html, but I want to do this programmatically using the DataTable initialization or API.
In my example below, I'm dynamically generating the column definitions directly from the json so I can avoid manually creating an html table in this same file. The code below works (although in real life the "my_data" value will come from an separate ajax call) but I can't figure out how to generate colspan. How can I programmatically generate the "HR Information" and "Contact" colspan items like https://datatables.net/examples/basic_init/complex_header.html,?
var my_data =
[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": 5421
},
{
"name": "Garrett Winters",
"position": "Director",
"salary": "5300",
"start_date": "2011/07/25",
"office": "Edinburgh",
"extn": "8422"
},
];
var my_columns = [];
function fillCols(dataSet) {
var x = dataSet[0];
$.each( x, function( key, value ) {
var my_item = {};
my_item.data = key;
my_item.title = key;
my_columns.push(my_item);
});
};
$(document).ready(function() {
fillCols(my_data)
$('#example').DataTable( {
data : my_data,
columns: my_columns
} );
} );
</script>
<table id="example" class="display" style="width:100%">
</table>
</html>
This question has an accepted answers - jump to answer
Answers
Datatables isn't going to create more than one header nor the colspan with
title
. Thetitle
is used to build the header row that Datatables will attach its event listeners to. You will need to build the HTML then append it to thetable
element.Kevin
Thank you. I used your suggestion along with some ideas from https://stackoverflow.com/questions/27447058/javascript-create-complex-table-header-from-json and I now have a working solution.