Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How to "attach" JSON to a button so that the data can be used when clicked on it

Using js, I make a request from which I get a json response. I loop through the list and add an html div for every object in the list. Each div contains elements that show a bit of info coming from that object (e.g. title, id, info, etc.). A button is also added to those divs that when clicked should make a request. The url that the request should be made to is in the json object for that div. See:

#json object for div
{
    "name":"Test1",
    "id":15,
    "link":"http://example.com"
}

#js to make div; object above is stored in obj
table = document.getElementById('div-list');

entry = document.createElement("div");
title = document.createElement("div");
title.innerHTML = obj.name;
entry.appendChild(title);

button = document.createElement("button");
button.innerHTML = 'Click me';
button.addEventListener("click", function() {
    data = {
        'id': [[  obj.id  ]]
    }
    fetch([[ obj.link ]], {
        method: 'POST',
        body: JSON.stringify(data)
    })
});
entry.appendChild(button);

table.appendChild(entry);

You can see the [[ obj.id|obj.link ]]. That is where the info from the json needs to go. However, doing obj.id or obj.link doesn't work because the function is run when clicked so the variable obj doesn't exist anymore. So I basically need to store the json in the entry-element so that when the button is clicked it can get it's info from somewhere.

I hopy you understand what I mean. Is there some way to allow that button-click-function access to "it's data" in order for it to determine where to send it's request to with what id?

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!