Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The calculator won't display the right results

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading