JavaScript: A dynamic table is created with columns populated by JSON data. The row structure is compromised

On my webpage, I pull in two sets of JSON data: 1) warehouses and 2) items. After receiving an Ajax search response from my view, I need to dynamically generate the TDs of a table based on the warehouses information.

The goal is to populate all TDs for every available warehouse listed in the JSON. If a product has stock at a particular warehouse PK, then I also want to display the quantity simultaneously.

                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>

                    [...]

Here is the resulting output: https://i.sstatic.net/KoLkx.png

I observed that even when I remove the "for i" loop, a <tr></tr> gets inserted between the two <td> elements. And when I reintroduce the loop, it causes a <tr> to appear between each <td>. Any insights into why this behavior occurs?

Answer №1

After scouring through various resources, I stumbled upon the functions insertRow() and insertCell() in JS that were completely new to me.

Despite my confusion over why using innerHTML <td> didn't yield the desired outcome, incorporating these two functions into my code proved to be the solution.

const tableBody = document.querySelector('.table-body');
var newRow = tableBody.insertRow(-1);  // Adds a new row at the end of the table
var newCell = newRow.insertCell(0);  // Places a new cell at index 0
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;
             }
         };
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selection determines the value of two fields

This form has predefined values that are used to create a link, but the issue is that these values vary depending on the location. Can you assist me with this problem? <input type="radio" id="iconapp1" name="department" value="1250"/><label for ...

Combining numerous inputs into an array in a React component

As a beginner in coding, I am eager to learn React by building a project. Currently, I am facing a challenge and seeking guidance. https://i.sstatic.net/Ic2zC.png My goal is to store all these values in an array structured as follows: { option: { s ...

Discovering ways to examine a React tree, view the props and state of components on Internet Explorer 11

After installing the React Developer Tools extension for Firefox and Chrome, I have been able to successfully utilize them. However, my struggle lies in not being able to locate a similar extension for Internet Explorer 11. Unfortunately, my application i ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...

Updating an AngularJS directive following a service method invocation

My goal is to set up a reusable alert service that can be easily called from anywhere in my application with just: alertService.showAlert('warning', 'something went wrong!'); One example of where I want to use this is after an AJAX ca ...

The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected. //Html <div id="mainapp"> <span class="star" v-bind:class="{ ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

How to efficiently use Yii2 and Ajax to insert data into a table twice in one

My form in Yii2 Advanced is inserting data twice into the table. When I click the submit button twice, the form inserts the data into the table twice as if I clicked the submit button two times consecutively. I am using ajax to submit my form. The code for ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

Access a portion of a file located on a distant server

Is it possible to read part of a remote file using Ajax without relying on server-side technologies like PHP? I believe the HTTP Range header could be utilized for this purpose, but how can we set it with Ajax? Can we even set HTTP headers in Ajax request ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

Ways to ensure a function is only triggered once using onmouseover

I'm fairly new to JavaScript and I've been attempting to create a function that only runs once. Here's the logo I've been trying to animate: <img src="img/logot2.png" id="logoutjs" onmouseover="move()" ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

Steps for retrieving a table of records with Jquery and sending it to the server through AJAX

Displayed below is a table I have: <table cellspacing="0" rules="all" border="1" id="ContentPlaceHolder1_GridView1" style="border-collapse:collapse;" class="table table-striped"> <tbody> <tr> <th scope="col"> ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Encountering a high volume of requests error while attempting to retrieve data from the API using the NodeJS backend, yet functioning properly on the React

While attempting to retrieve data from https://api.solscan.io/chaininfo using a NodeJS backend application, I encountered an error stating 429: Too many requests. Interestingly, the same API functions without any issues when utilized in a React frontend a ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...