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

Nested pages in the NextJS router do not properly highlight the active menu item

I am currently working with NextJS and facing an issue with setting active menu items using the router. While the 'top level' pages behave as expected, any page under a top level page does not get set as active. router.pathname == "/profile& ...

What sets apart $document from $window.document in Angular?

After experimenting with the code on JSBin, I noticed that the first snippet successfully retrieved the canvas object, while the second one did not. JSBin: http://jsbin.com/natavejasa/1/edit?html,js,output var canvas = $window.document.getElementById(&ap ...

The webpage is failing to refresh even after using history.push()

While working on my React dictionary project, I encountered an issue with React Router. After using history.push() with the useHistory hook from react-router, the page does not re-render as expected. I have a search bar and utilize this function to navigat ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

Tips for sending dynamic column and row information to antd table

The following code does not seem to work for an array containing rows and columns Below is an example using antd: const data = []; for (let i = 0; i < 4; i++) { data.push({ key: i, name: `Edward King ${i}`, age: 32 // address: `London ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...

Unexpected error: The 'try!' expression has caused a fatal error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "hours", intValue: nil)

I encountered a strange error that I am unable to comprehend. The issue arose only after adding a new item. Here is the error message: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stri ...

Is there a way to set a custom width or make the description responsive?

Is there a way to ensure that the description is responsive and automatically goes to the next line instead of extending horizontally? Although using textField could fix this issue, I also need to adjust the padding and outline. Are there any alternative s ...

What is the best way to retrieve the "name" and "ObjectId" properties from this array of objects? (Using Mongoose and MongoDB)

When trying to access the name property, I encountered an issue where it returned undefined: Category.find() .select("-_id") .select("-__v") .then((categories) => { let creator = req.userId; console.log(categories.name) //unde ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

The necessity of utilizing a dummy object for storing events in JavaScript is evident in certain situations

I am confused as to why in some instances a dummy object is needed in JavaScript to store events, like in the following code: Metal.Gold = function() { var temp = $("<div>"); //dummy object this.Submit = function(url1, method, data){ ...

When the user clicks the back button in AngularJS

After searching extensively, I have yet to find a straightforward solution to my issue. The problem lies in a search/filter field that filters the page based on user input. While this filter works efficiently, it clears whenever a navigation item is clicke ...

What is the reason behind the failure of the cancel test?

I've created two test cases; one for testing the functionality of the Download button and the other for the Cancel button. However, I am encountering issues with the Cancel test failing consistently. Below is the code snippet where I'm attemptin ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

Converting a Luxon DateTime object into a standard date

Currently, I am constructing a DatePicker React component utilizing the Material-UI picker library and integrating Luxon as an adapter. Whenever I modify the calendar date, I receive an object containing DateTime information as shown below: This is the co ...

Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. ...

Exploring the concept of Model Binding in WebAPI through JSON Data

Currently, I am in the process of developing an application using Durandal along with WebAPI as the server. Everything seems to be running smoothly until the POST or PUT methods are invoked while working with a KendoUI grid. The data from the server displa ...

Navigating the nuances of working with nullable and non-nullable types using generics

Developing a specialized LookupConverter : JsonConverter class was essential for efficient JSON serialization and deserialization of ILookup objects. Given the complexities arising from dealing with generics and the lack of a public concrete Lookup class, ...