0

I am trying to make a small calculator with Javascript, but the two numbers are not added or subtracted, it just gets concatenated, for example, if I want to add 2+2 it outputs " 22" not 4. , here is the code:

    <!DOCTYPE html>
    <html>
    <head>
   <title>Hello!</title>
   </head>
   <script>

  function getResult()
  {
  var result1 = document.getElementById("number1").value;
  var result3 = document.getElementById ("op1").value;

   var result2 = document.getElementById("number2").value;

    calculate (result1,result3,result2);
   }

  function calculate(num1,operator,num2)
   {

   if (operator== '+')
   {
    var res1 = num1+num2;
    alert(res1);

    }
   else if (operator== '-')
   {
    var res2 = num1-num2;
    alert(res2);

    }
    else if (operator== '*')
    {
    var res3 = num1*num2;
    alert(res3);

    }
   else if (operator== '/')
    {
    var res4 = num1/num2;
    alert(res4);
     }

   else
     {
    alert("Nothing from above!");
    }

    }
    </script>

    <body>
    <form action="get" method="#">
    <input type="text" name="text1" value="" id="number1"  />
    <input type="text" name="text2" value="" id="number2" />  <br />

  <input type="button" name="o1" value="+" id="op1" onclick="getResult();"/>
  <input type="button" name="o2" value="-" id="op2" onclick="getResult();"/>
  <input type="button" name="o3" value="*" id="op3" onclick="getResult();"/>
  <input type="button" name="o4" value="/" id="op4" onclick="getResult();"/>      

 <input type="button" name="calc" value="Calculate" onclick="getResult();"/>
 </form>

 </body>
 </html>
0

4 Answers 4

1

In JavaScript (and in many other programming languages), when you add two strings together, you get the concatenation of their values. Currently your program is treating the form inputs as strings, but you can use the built-in function parseInt to extract integers from Strings.

Try the following:

function getResult() {
    var result1 = parseInt(document.getElementById("number1").value);
    var result3 = parseInt(document.getElementById ("op1").value);
    var result2 = parseInt(document.getElementById("number2").value);

    calculate (result1,result3,result2);
}
Sign up to request clarification or add additional context in comments.

Comments

0

apply parseFloat, example

var res1 = parseFloat(num1)+parseFloat(num2);

Comments

0

That is because of string concatenation. Please change the code to var res1 = parseInt(num1) + parseInt(num2);

Comments

0

You must cast your vars to ints before doing any math with them. By default they are read in as strings. result1 = parseInt(result1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.