Search code examples
javascriptajaxhtml-tableinnerhtml

Javascript : Table columns build dynamically with JSON datas. Row structure broken


I retrieve on my page 2 sets of data (json): 1: warehouses 2: items. With the first I wan't to create dynamically the TD's of my table after getting an Ajax search response from my view.

I want to create all TD for all warehouses available in the warehouses JSON and if a product has a stock on this warehouse PK, in the same time, I populate the QTY

                tableBody.innerHTML += `
                    [...]
                     
                    <td>${item.fournisseur__nom}</td>`;
                JSON.parse(warehouses).forEach((wh) => {
                        tableBody.innerHTML += `
                        <td>
                        `;
                        for (let i = 0; i < item.sststock.length; i++) {
                            if (item.sststock[i].sst_id == wh.pk) {
                                tableBody.innerHTML += item.sststock[i].qty;
                            }
                        };
                        tableBody.innerHTML += `
                        </td>
                        `;
                    });

                tableBody.innerHTML += `   
                    <td>${item.qty}</td>

                    [...]

Alas, here the result : enter image description here

I noticed that even if I remove the loop "for i", a <tr></tr> is inserted between the 2 <td> and when I put the loop back, between each <td>, a <tr> raises. Any idea about the reason of this behaviour ?


Solution

  • Despite multiple previous searches, I hadn't heard yet about insertRow() and insertCell() in JS.

    Even if I still don't understand why innerHTML <td> didn't work, I changed my code with these 2 functions and result is OK.

    const tableBody = document.querySelector('.table-body');
    var newRow = tableBody.insertRow(-1);  // -1 = at the end of the table
    var newCell = newRow.insertCell(0);  // 0 = at the 0 index
    newCell.innerHTML = item.etat;
    [...]
    JSON.parse(warehouses).forEach((wh) => {
             var newCell = newRow.insertCell(-1);
             for (let i = 0; i < item.sststock.length; i++) {
                 if (item.sststock[i].warehouse_id == wh.pk) {
                     newCell.innerHTML = item.sststock[i].qty;
                 }
             };
        });