Home > Software design >  The data is not inserted correctly in the table tbody tag
The data is not inserted correctly in the table tbody tag

Time:02-14

I'm having a problem setting the body in the dynamic content table.

In fact, thead has been set correctly, but most likely the problem is the tbody; the header of the columns is perfectly displayed, but the content is not.

See image below (Nessun dato presente nella tabella --> No data in the table)

Can anyone kindly help me?

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {               
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.titolo}</td>
                    <td>${item.marca}</td>
                    <td>${item.immagine}</td> 
                    <td>${item.sezione}</td>
                    <td>${item.data}</td>
                    `;
                    table.appendChild(child);
                })
                tbdy.appendChild(tr);
                table.appendChild(tbdy);
                
$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });
<table id="my-table"  width="90%">
        <thead>
            <tr>
                <th >Id</th>
                <th >Titolo</th>
                <th >Marca</th>
                <th >Immagine</th>
                <th >Sezione</th>
                <th >Data</th>

            </tr>
        </thead>

    </table>

CodePudding user response:

you need to append tr with tbody inside the loop.

allart.Items.forEach(function (item) {
    let child = document.createElement("tr");
    child.innerHTML = `
                <td>${item.id}</td>
                <td>${item.titolo}</td>
                <td>${item.marca}</td>
                <td>${item.immagine}</td> 
                <td>${item.sezione}</td>
                <td>${item.data}</td>
                `;
    tbdy.appendChild(child);
})
table.appendChild(tbdy);
  • Related