I am fairly new to JavaScript but today I stumbled upon a weird issue that I would really appreciate if someone could shed some light on for me.
I am working on a calculator in HTML. I have one function in js that I use for an onclick event on a div. That div works like a backspace button with the following code:
function remove() {
var input = document.getElementById("input");
input.innerHTML = input.innerHTML.substring(0, input.innerText.length - 1);
// Check if comma exists
if (input.innerHTML.indexOf(",") == -1) {
comma = false;
}
}
It removes the last added number from the innerHTML of my paragraph, like it should. However, doing that exact same thing in the following function somehow removes two characters from the paragraph instead of one:
function buttonOperator(operator) {
var input = document.getElementById("input");
var calc = document.getElementById("calculation");
// Make sure new number isn't empty and fits into the calculation
if (input.innerHTML != "") {
// Bunch of code
}
else {
// This line removes two characters instead of one
calc.innerHTML = calc.innerHTML.substring(0, calc.innerText.length - 1);
operators.pop();
switch (operator) {
case "÷":
calc.innerHTML += "÷";
operators.push("÷");
break;
case "×":
calc.innerHTML += "×";
operators.push("×");
break;
case "−":
calc.innerHTML += "−";
operators.push("−");
break;
case "+":
calc.innerHTML += "+";
operators.push("+");
break;
}
}
input.innerHTML = "";
comma = false;
}
The function's purpose is to remove the already existing operator at the end of the paragraph and replace it with a new one. But removing the last character the same way I did in my remove function somehow removes two characters.
If I have:
98 +
Pressing, for example, plus again would leave the following:
98+
And again:
9+
etc.
I really don't understand how this can possibly happen. If someone could explain it to me for future reference I would highly appreciate it.