Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload().

I've tried numerous approaches, but none seem to be working for me.

Below is the code I've been working with. If you can offer some guidance, I'd really appreciate it. Just show me how to do it, instead of simply providing the finished code.

HTML

<div>
    <button>Get</button>
    <div id="table"></div>
</div>
<script src="script.js"></script>
</body>
</html>

JS

let myTable = document.querySelector('#table');


var distribuidores;
fetch('http://localhost:3000/distribuidores')
    .then(res => res.json())
    .then(data => distribuidores = data)
    .then(() => console.log(distribuidores))

let headers = ['id', 'codBrid', 'descricao']

btnGet.addEventListener('click', () => {
    let table = document.createElement('table');
    let headerRow = document.createElement('tr');

    headers.forEach(headerText => {
        let header = document.createElement('th');
        let textNode = document.createTextNode(headerText);
        header.appendChild(textNode);
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    distribuidores.forEach(emp => {
        let row = document.createElement('tr');
        Object.values(emp).forEach(text => {
            let cell = document.createElement('td');
            let textNode = document.createTextNode(text);
            cell.appendChild(textNode);
            row.appendChild(cell);
        });

        table.appendChild(row);
    });

    myTable.appendChild(table);
});

json

{
       "distribuidores": [
        {
            "id": "1",
            "codint": "4613",
            "descricao": "HTMYS"
        },
        {
            "id": "2",
            "codint": "10325",
            "descricao": "MPB LTDA"
        }
    ]
}

Answer №1

After adding an id to the button, your code functions perfectly

let myTable = document.querySelector('#table');


var distribuidores = [
        {
            "id": "1",
            "codint": "4613",
            "descricao": "HTMYS"
        },
        {
            "id": "2",
            "codint": "10325",
            "descricao": "MPB LTDA"
        }
    ];


let headers = ['id', 'codBrid', 'descricao']

btnGet.addEventListener('click', () => {
    let table = document.createElement('table');
    let headerRow = document.createElement('tr');

    headers.forEach(headerText => {
        let header = document.createElement('th');
        let textNode = document.createTextNode(headerText);
        header.appendChild(textNode);
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    distribuidores.forEach(emp => {
        let row = document.createElement('tr');
        Object.values(emp).forEach(text => {
            let cell = document.createElement('td');
            let textNode = document.createTextNode(text);
            cell.appendChild(textNode);
            row.appendChild(cell);
        });

        table.appendChild(row);
    });

    myTable.appendChild(table);
});
<html>
<body>
<div>
    <button id=btnGet>Get</button>
    <div id="table"></div>
</div>
</body>
</html>

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

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

Transforming a Shadertoy experiment into a customized Three.js playground on my local machine

I am currently working on a local shader sandbox project inspired by a Shadertoy created by lennyjpg. I have been referencing two Stack Overflow questions and answers (one, two) for help. The goal is to convert the Shadertoy code to use Three.js for a larg ...

Considering a Servlet for managing AJAX requests?

Looking for advice on best practices for implementing a yes or no question with AJAX requests. Open to feedback if I make any missteps along the way. I have a specific Servlet (AjaxServlet?) designated to handle all AJAX requests AjaxServlet is mapped t ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Utilizing the "each" function in jQuery to create click events for buttons that are linked to specific paragraphs

Right now, I am facing a situation where I have three buttons, each assigned with an ID that matches their order. Upon clicking a button, the paragraph associated with that order should hide itself using .hide(). My challenge lies in finding out how to ut ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

Retrieving ng-model using ng-change in AngularJS

Here is an example of the HTML code I am currently working with: <select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select> This HTML snippet is being populated by the following object containing a ...

Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet. Is there an alternative method to optimize this process without utilizing map? Code: const arr = [{ label: 'A', ...

Tips for troubleshooting Grunt in PHPStorm (or WebStorm)

Looking for tips on debugging grunt, such as using an event listener function, in PHP Storm. Does anyone have any ideas? I know that PHP Storm has Node.js support, but I'm not sure how to configure debug settings for debugging a grunt task. For examp ...

Looking to split the month and year input boxes when utilizing stripe version 7.2.0

Currently, I am utilizing ngx-stripe Version 7.2.0 to manage UI elements in Angular. I'm wondering if there is a method to split the Month and Year into separate text boxes within the UI of Angular 7 instead of having them combined into one field? ...

Fullcalendar Unable to Show JSON Events on Feed

It seems like a common issue, but I've been unable to find a solution yet. I'm currently testing Fullcalendar with Scheduler on my local server. I'm attempting to replace the static data feed that's an array with data fetched from a My ...

forever js is interfering with the operation of a different application

I currently have two very similar Node JS projects that I manage by starting and stopping them using Forever JS. Both projects can run simultaneously on different ports but, when I input the following command: forever stop index.js In one project direc ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Simple C++ library designed for newcomers to interact with RESTful APIs

Looking for a user-friendly library to work with Dropbox's REST API in C++. What specific functionalities will I require? (Limited knowledge of REST APIs) I know I'll need HTTP protocol and XML parsing capabilities, but what about JSON? Aside f ...

The jQuery $.getJSON function encountered an error and was unable to load the resource, displaying the message "Failed to

I'm encountering a challenge while trying to load a JSON resource from a local Rails application using jQuery 1.4.4. The JSON is confirmed to be valid (verified using jsonlint.com) and I am able to successfully download it when requesting it from oth ...

Guide on selecting every input field located within a table

My form is embedded within a table <form id="form"> <input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input> <table class="table table-strip ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: https://i.sstatic.net/DM8sX.png And this is how I want it to appear: https://i.sstatic.net/BXGpW.png Is there a way to achieve the ...

Preventing scrolling on a YouTube video embed

I have been working hard on developing my personal website. One issue I encountered is that when there is a YouTube video embedded in the site, it stops scrolling when I hover over it. I would like the main document to continue scrolling even if the mouse ...

Persistent change issue with JQuery CSS function

Looking for some help with a button-bar div that I want to display only after the user clicks on a "settings" button. Currently, I have set the button-bar div to have a display:none property in my css file. However, when the settings button is clicked, t ...

Achieving peak efficiency: Comparing the execution of actions through dispatching versus passing them as props

I have a technical query. I'm attempting to send a value from a child component to the store by utilizing an action dispatcher inside the child component. This action dispatcher then modifies the state value in the reducer. Would it be wise to pass v ...