Reputation: 557
So I have this code:
var add, substract, multiply, divide;
var calculation = {
add: {
place: 2,
name: add,
calculation: function (a,b) {return a + b;},
output: function (a,b) {return a + ' + ' + b;},
buttonHTML: '+'
},
substract: {
place: 2,
name: substract,
calculation: function (a,b) {return a - b;},
output: function (a,b) {return a + ' - ' + b;},
buttonHTML: '-'
},
multiply: {
place: 1,
name: multiply,
calculation: function (a,b) {return a * b;},
output: function (a,b) {return a + ' * ' + b;},
buttonHTML: '*'
},
divide: {
place: 1,
name: divide,
calculation: function (a,b) {return a / b;},
output: function (a,b) {return a + ' / ' + b;},
buttonHTML: '/'
},
};
document.getElementById("calculator").innerHTML=('
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
};');
In my html file the script is loaded in the head elements. In body I have a div element named calculator. Now what I want to do is to create buttons inside of that div element with the loop I have. But what I have written seems to not work and I fail to find any better solution too. Any ideas?
Upvotes: 0
Views: 45
Reputation: 1871
Just for the numbers 0 to 9 the following function will add the required buttons inside a div with a known id. It will not necessarily position them as you need nor get them to respond as you require but it should get them into the div.
function insertNumberButtons(id) {
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById(id).appendChild(btn);
}
}
Upvotes: 1
Reputation: 6167
The function that creates the buttons looks fine to me. The only thing is: it's not a function, and it doesn't get executed anywhere. Instead, it's assigned as a string to innerHTML
. That won't work. Instead, use this:
window.onload = function () {
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById("calculator").appendChild(btn);
}
};
Upvotes: 2