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?