Creating a table in HTML to display the elements of an array in rows and columns

I am facing an issue where all elements of an array are being placed in the first table column instead of distributing them into corresponding columns. I believe a simple nested for loop might be the solution, but I'm uncertain. Any assistance would be greatly appreciated. Thank you!

index.html

<div id="PersonContainer" class="DBcontainer">
        <form action='/addPerson' method="GET"></form>
        <table class="center" id="personTable">
            <caption>People Table</caption>
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Hooks ID</th>
                    <th>Soft Plastic ID</th>
                    <th>Rods ID</th>
                    <th>Number of Hooks</th>
                    <th>Number of Soft Plastics</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <button type="button" onclick="displayPerson()">Click Me</button>
        </form>

    </div>

index.html script

<script>
        function displayPerson() {
            // console.log('test');
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var person = xhttp.responseText;
                    var element = document.getElementById("personTable");
                    var result = JSON.parse(person).map((item) => Object.values(item));
                    for(i = 0; i < result.length; i++){
                        element.innerHTML += '<td>' + result[i] + '</td>';
                    }
                }
            };
            xhttp.open("GET", "/AddPerson", true);
            xhttp.send();
        }
    </script>

the xhttp.responseText

[{"id":1,"first_name":"Tyler","last_name":"Marlow","hooks_id":1,"sp_id":1,"rods_id":1,"num_hooks":10,"num_sp":30},{"id":2,"first_name":"Jon","last_name":"Marlow","hooks_id":2,"sp_id":1,"rods_id":1,"num_hooks":50,"num_sp":200}]

Lastly, please note that when adding another person, it is expected to append a new row with values distributed correctly in respective columns.

Answer №1

To append a new row to a table using JavaScript, you can utilize the insertRow function. Similarly, adding a cell to a row can be achieved through the insertCell function.

When implementing this in your code (considering the structure of your parsed JSON), within your for loop you would typically execute something along the lines of:

row = element.insertRow(i); // add a new row to the table row.insertCell(0).innerHTML = row.insertCell(1).innerHTML = and continue with additional cells .... However, it is important to iterate over the insertCell line within another for loop if needed.

Answer №2

function fetchUser() {
  // console.log('test');            
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var user = request.responseText;
      var container = document.getElementById("userTable");
      var rows = ``;
      JSON.parse(user).forEach(item => {
        var row = `<tr>`;
        row += `<td>${item.first_name}</td>`;
        row += `<td>${item.last_name}</td>`;
        row += `<td>${item.hooks_id}</td>`;
        row += `<td>${item.sp_id}</td>`;
        row += `<td>${item.rods_id}</td>`;
        row += `<td>${item.num_hooks}</td>`;
        row += `<td>${item.num_sp}</td>`;
        row += `</tr>`;
        rows += row;
      });
      container.innerHTML = rows;
    }
  };
  request.open("GET", "/FetchUser", true);
  request.send();
}
<div id="UserContainer" class="DBcontainer">
  <form action='/fetchUser' method="GET">
    <table class="center">
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Hooks ID</th>
          <th>Soft Plastic ID</th>
          <th>Rods ID</th>
          <th>Number of Hooks</th>
          <th>Number of Soft Plastics</th>
        </tr>
        <thead>
          <tbody id="userTable">
          </tbody>
    </table>

    <button type="button" onclick="fetchUser()">Click Me</button>
  </form>
</div>

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

Endless invocation of AngularJS $http requests

Could someone kindly clarify why the $http request is continuously sending an infinite number of requests to the server in my application? The code snippet provided is causing this issue: (function(){ var app = angular.module("GrahamsSocksProducts", [ ...

Retrieving data from router in Angular

I have been working on a web application using Angular, and I have implemented a fixed header in the index.html file. The header appears on every page, with content injected through a ui-view. However, I now want to display this header only after the user ...

What is the process for updating or upserting a document in Mongoose?

Maybe it's the timing, maybe it's me struggling with sparse documentation and not quite grasping the concept of updating in Mongoose :) Let's break it down: I have a contact schema and model (abbreviated properties): var mongoose = requir ...

Guide on integrating CSS into a Vue Bootstrap table design

I am having trouble adding a CSS to my bootstrap vue table template. <template slot="actions" slot-scope="data" :style="{min-width:'150px'}"> <b-button variant="info" @click="showViewModel(data.item)"> <i class="fa fa-e ...

Sort through an array containing JavaScript objects in order to filter out certain elements that match a different

Below is a fictional JavaScript array made up of objects: const permissions = [ { moduleEnabled: true, moduleId: 1, moduleName: 'Directory' }, { moduleEnabled: true, moduleId: 2, moduleName: 'Time off' } ...

Utilize PHP to import hierarchical JSON data into MySQL database along with establishing relationships

Is there a straightforward solution to importing nested JSON data into multiple MySQL tables? The challenge is that JSON lacks bidirectional relations, so they need to be generated automatically. Check out this sample data: [ { "targetgro ...

Styling input groups with box shadows in Bootstrap 4

One issue I am encountering is the focus shadow that appears when the input text is focused. My goal is to have both the text input and the right button display a focus border. To illustrate this problem, I have created a JSfiddle: http://jsfiddle.net/a5u ...

Access and alter SVG files using Node.js

We have a special API that is designed to send PNG files. These PNG files are created by combining multiple SVG files and making various changes to attributes such as background color and image size. Our server side technology of choice is Node.js. I att ...

The use of the <span class="blinking"> element is not functioning properly within the JavaScript

<body class="container-fluid"> <div class="panel panel-primary"> <div class="panel-heading"> <h3>Body Temperature</h3> </div> <div class="panel-body"> <p>Your body temperature is hig ...

Tips for integrating my Python random forest classifier in a web application built using HTML, Javascript, and Node.js

Greetings! I am currently in the process of creating a machine learning web application that requires the use of a random forest classifier. However, I am unsure of how to properly integrate the python code with it. Any guidance would be greatly apprecia ...

Using a local variable within quotes in Angular 4 (HTML) and utilizing ngFor

In my current project, I am utilizing Angular2-Collapsible. The objective is to display the details upon clicking a table row. Below is the code snippet provided. Specifically, if I add [detail]= "detail1", the collapsible-table-row-detail will appear when ...

What causes the undefined value in my HapiJS test utilizing the Lab library?

Currently, I am diving into the HapiJS tutorial to build a server and incorporate unit testing. 'use strict' const Hapi = require('@hapi/hapi') module.exports = async (host, port, router) => { if (!host) { const error = new E ...

Retrieve the VSTS Service Link for Kubernetes

I am currently in the process of constructing a pipeline for Kubernetes within VSTS. My NodeJS tests utilize kubernetes-client to ensure proper deployment. Regarding the deployment itself, we have established two service connections. I aim to access kube ...

Nodemailer Emails Are Being Sent with an Incorrect 'From' Address

In my Node.js application, I am using the nodemailer library to send emails. However, I am facing an issue where the 'from' address is not being set dynamically based on the current user's email. Instead, all emails are consistently being se ...

Nextjs 13.4: GET request with parameters results in a 404 error

Hey, I'm having some trouble trying to send a fetch request with the parameter id to my API. The id is a string and I am using a dynamic route folder [...id] in the Link element. The Link Element <Link href={`/books/${id}`}">Book Number {i ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

Is iOS Safari automatically filling all fields with identical information?

I'm in the process of creating a basic form that allows users to input their name/email and their friend's name/email. The code snippet can be found below. Interestingly, while most browsers autofill only the first two fields, iOS Safari on my i ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Is there a way to position the navbar at the bottom of the page?

Is there a way to position this navbar at the bottom of the page? I've tried using different properties like bottom or margin-bottom, but it doesn't seem to work. Could there be a CSS configuration preventing these commands from taking effect? H ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...