0

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));
    }
});

1 Answer 1

1

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.