I am trying to create a calculator with buttons from 0 to 9. I created the buttons from code and I wanted the 0
button to append 0
to the display, the 1
button to append 1
, etc. However, every button appends 3
to the display.
I made this minimal example to illustrate the problem:
var myDisplay = document.getElementById("display");
for (var i=0; i<3; i++){
var elem = document.getElementById("buttons");
elem.appendChild(newButtonWithText(i, function(){myDisplay.value += i;}));
}
function newButtonWithText(text,fun){
var btn = document.createElement("button");
var t = document.createTextNode(text);
btn.appendChild(t);
btn.className= "btn btn-default";
btn.onclick = fun;
return btn;
}
<input id="display"></input>
<div id="buttons"></div>