Reputation: 105
I create a table with ajax, but can't seem to enclose the <th>
elements inside the <tr id="header">
. I've tried the appendTo
, prependTo
, but no luck.
The structure I want is: <Table><Thead><tr><th>
, so that the data that would go in th
would be children to #header
, not siblings
function arrayToTable(tableData) {
var table = $('<table id = "data_table"></table>');
$(tableData).each(function (i, rowData) {
if (i==0){
var row = $('<thead class= "table_header"><tr id="header"></tr></thead>');
$(rowData).each(function (j, cellData) {
$('#header').append($('<th>'+cellData+'</th>'));
});
table.append(row);
} else{
var row = $('<tr class="table_data"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
}
});
return table;
}
$.ajax({
type: "GET",
url: "random/folder/with/csvs/csv1.csv",
success: function (data) {
$('#container').append(arrayToTable(Papa.parse(data).data));
}
});
Upvotes: 0
Views: 207
Reputation: 632
Try this code
$(tableData).each(function (i, rowData) {
if (i==0){
var head = $('<thead class= "table_header"></thead>');
var row = $('<tr id="header"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<th>'+cellData+'</th>'));
});
head.append(row);
table.append(head);
} else{
var row = $('<tr class="table_data"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
}
});
Upvotes: 1