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

303
Views
Creating different instances of a function to be called later in javascript

Im trying to implement a dashboard in javascript, and am having some trouble with one of the components.

My code recieves a list of servers from an api, and I create and copy of a list item for each.

for (var i = 0; i < userData.servers.length; i++) {
      var server = userData.servers[i];
      var clone = serverElement.cloneNode(true);
      
      var serverImage = clone.getElementsByClassName("server-image")[0];
      var serverName = clone.getElementsByClassName("server-name")[0];
      var serverSelect = clone.getElementsByClassName("server-select")[0];
      
      serverName.innerText = server.name;
      serverImage.src = "https://cdn.discordapp.com/icons/" + server.id + "/" + server.icon + ".png?size=128";

      serverSelect.innerText = "Select";
      serverSelect.onclick = () => { setPremiumServer(server.id) };
      
      serverList.appendChild(clone);
}

However an issue arises with setting the onclick function of the button 'serverSelect'.

serverSelect.onclick = () => { setPremiumServer(server.id) };

When a button on one of the list items is pressed, I want it to call 'setPremiumServer' with the parameter being the ID corresponding to the server represented by the list item.

The way I attempted to do this was by creating an instance of a function, with the value set inside of it.

However, it appears this code isnt evaluated until the button is pressed, at which point it calls setPremiumServer() with the ID of the server that appears last in the list.

How would I fix this, and make it correctly call the function with the ID of the server represented by the list element?

about 4 years ago · Juan Pablo Isaza
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!