I would like to ask a bit of help. I was creating a simple calculator. The problem is my calculator displays the same results everytime. The addition would display nothing, the subtraction and multiplication would display 0, and the division and modulo would display NaN. Here is my code:
let a = document.getElementById("num1").innerHTML;
let b = document.getElementById("num2").innerHTML;
function addFunction() {
let add = a + b;
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = a - b;
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = a * b;
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = a / b;
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = a % b;
document.getElementById("result").innerHTML = modulo;
}
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1">
<input id="num2">
<br>
<br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
>Solution :
You should get values of input not innerHTML like this
var a = document.getElementById("num1").value
var b = document.getElementById("num2").value
And then convert it to number like this
a = parseFloat(a)
b = parseFloat(b)