0

I am new to js and I am confused. So, I created a calculator using HTML and Javascript. I have code below.

function cal() {
    let num1 = document.getElementById("num1").value;
    let num2 = document.getElementById("num2").value;
    let sign = document.getElementById("sign").value;

    let num3 = document.getElementById("result");

    if(sign == "+") {
        var I;
        i = num1 + num2
        num3.innerText = I;
    } else if(sign == "-") {
        var x;
        x = num1 - num2
        num3.innerText = x;
    } else if(sign == "*") {
        var a;
        a = num1 * num2
        num3.innerText = a;
    } else if(sign == "/") {
        var b;
        b = num1 / num2
        num3.innerText = b;
    }
}
<h1>
    Calculator
</h1>

<input id="num1" placeholder="first number">
<input type="text" id="sign" placeholder="sign">
<input id="num2" placeholder="second number">
   

<button id="summit" onclick="cal()">
    Enter
</button>

<h3 id="result"></h3>

Everything worked but when I use the operator "+" I got something like this: Image

Am I missing something? Other operators work fine. Can someone please explain to me and tell me how to get value using "+"?.

julianstark999
  • 3,450
  • 1
  • 27
  • 41
infinite
  • 19
  • 2
  • 1
    `i = +num1 + +num2` you must convert to number – user120242 Jun 16 '20 at 04:33
  • In `if` condition you declared `var I` `(I in the capital)` and you assigned to `i = num1 + num2` `(i in small letter)`. Remember javascript is a **Case Sensitive** language. – Sateesh Gollapudi Jun 16 '20 at 04:37
  • document.getElementById("num1").value would return a string value, so before the math operation convert the string in to integer by using parseInt() as i = parseInt(num1) + parseInt(num2) – Rejayi CS Jun 16 '20 at 04:40

0 Answers0