Forgive me for the broad title, I'm not sure how to state my problem.
I have a JS function that iterates through an array to create/append elements in a div. Each element is given an onclick function, however, when the onclick is executed, only the last iteration is recognized.
Here's an example of what I mean: (or check out this fiddle)
while(n--){
myBtn = this.myButtons[n];
btn = document.createElement("input");
btn.setAttribute("type","button");
btn.setAttribute("value",myBtn.name);
btn.onclick = function(){
window.alert(myBtn.msg);
}
div.appendChild(btn);
}
Here, I loop through an array of Javascript objects, create a button for each one and assign an onclick function which alerts the name of the object, however it always alerts the name of the last object instead of the name of the object which correlates with the given button. Check the fiddle to see what I mean.
How can I alter my fiddle to have it alert the correct message for each button?