I am looping through an array of objects and i'm experiencing strange behavior. Here is my code:
window.onload = function () {
document.getElementById('btnAdd').onclick = function () {
add("button");
};
function add(type) {
var names = {};
names['one'] = { id: "Button 1",msg:"#1" };
names['two'] = { id: "Button 2", msg: "#2" };
names['three'] = { id: "Button 3", msg: "#3" };
//Create an input type dynamically.
function addOnClick(element, currentName) {
element.onClick = function () {
alert("button is " + names[currentName].msg);
};
};
for (name in names) {
var element = document.createElement("input");
element.type = type;
element.value = names[name].id;
element.name = name;
addOnClick(element,name);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
}
};
Heres the html:
<p>
<input type="button" id="btnAdd" value="Add Buttons" />
<p id="fooBar">Buttons: </p>
</p>
If you run this in your browser, and the "Add Buttons" button, 3 buttons are created and named appropriately. But if you click one of the 3 new buttons, the alert box always says "button is #3" and i have no idea why. Can someone explain why the onClick event is only remembering the last item in my array? Thanks
element.onclicknotelement.onClick