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);
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.