I'm writing a simple JavaScript form, it is a list of devices with a button next to each where the button should take you to a text field where you can edit info about a device. Instead all of the buttons take you to the info for the last device on the list. Here is the snippet where I'm creating the list:
for(var i in portal.clients){
var row = document.createElement('tr');
var cell2 = document.createElement('td');
var button = document.createElement('button')
var title = document.createTextNode("Edit Config")
button.appendChild(title)
button.onclick = function(){displaySettingsPage(portal.clients[i]); console.log("Showing client: " + clientNum)}
cell2.appendChild(button)
row.appendChild(button)
var cell1 = document.createElement('td');
var client = document.createTextNode(portal.clients[i].info.description.name)
cell1.appendChild(client)
row.appendChild(cell1)
table.appendChild(row);
}
I assume the problem is that the i
in the onClick
function declaration is getting evaluated when the button is clicked instead of when the function is declared like I meant it to. Is there a way that I can force a variable to be evaluated when the function is declared? Or is there some other method that I should use to pass the client index to the function?