while building a fairly simple calculator I have encountered the issue of an array+function generated buttons not reacting to a click all though they have an onclick event tag.
HTML:
<div class="calculator">
<div class="monitor">
<div id="prev-line">0</div>
<div id="current-line">0</div>
</div>
<div id="pad"></div>
</div>
JS:
const buttons =["1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "+", "-", "*", "/", "=", "DEL", "AC"];
let text = "<button oncliclk='execute()'>0";
buttons.forEach(myFunction);
text += "</button>";
document.getElementById("pad").innerHTML = text;
function myFunction(value){
text += "<button oncliclk='execute()'>" + value + "</button>";
}
var previous = document.getElementById("prev-line");
function execute() {
var buttonValue = event.target.textContent;
var previousLineVar = previous.innerText;
var currentLineVar = document.getElementById("current-line");
switch (buttonValue) {
case 'DEL':
previous.innerText = previous.innerText.slice(0, -1)
break;
case '=':
previous.innerText = `(${previousLineVar})`
currentLineVar.innerText = `${eval(previousLineVar)}`
break;
case 'AC':
previous.innerText = ''
currentLineVar.innerText = ''
break;
default:
previous.innerText = `${previousLineVar}${buttonValue}`
break;
};
}