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

155
Views
getting variable from loop to function

so I was working on discord bot dashboard and I am trying to make redirect buttons that goes to discord server user selects. So I am trying to make dynamic address like: http://localhost:3000/dash/discord/servers/${guildid}, but when I get the guild id and try to pass it on button.onclick function I just get 3 and not ex. 1,2,3. Everything is in a loop so I am little bit confused. Please help!

All of the code is in html file - script

Loop code:

document.addEventListener('DOMContentLoaded', function () {

     for (var i = 0; i < guildsLength; i++) {

        var button = document.createElement('button');
        button.type = 'button';
        button.innerHTML = Guildss[i] + " ID: " + IDs[i];
        button.className = 'btn-styled';
        button.id = 'b1';
        button.onclick = function (){

           location.href = `http://localhost:3000/dash/discord/servers/${IDs[i]}`

        }

        document.body.appendChild(button);

     }

  }, false);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're getting always the last i value because of javascript closures. When onclick method is called, it access i variable defined in its outer function, and at that moment i has the value that had when for loop finished.

You could use <a> tags and store the url in href attribute. This way you don't need any callbacks, and if you want, you can style the anchor as a button.

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