Search code examples
javascripthtmlcalculatorcalc

How can I make this calculator work


I am having trouble, as you can see in code, for the result3 as id i have op1, what I would like to have there so that it works is that id changes depending on the button pressed, how can I do that? because now every button is like a +.

<!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 = parseFloat(num1)+parseFloat(num2);
        alert(res1);
      }
    else if (operator== '-')
      {
        var res2 = parseFloat(num1)-parseFloat(num2);
        alert(res2);
      }
    else if (operator== '*')
      {
        var res3 = parseFloat(num1)*parseFloat(num2);
        alert(res3);
      }
   else if (operator== '/')
      {
        var res4 = parseFloat(num1)/parseFloat(num2);
        alert(res4);
      }
   else
      {
        alert("Nothing from above!");
      }

  }
    </script>

    <body>
      <form action="get" method="#">
        <input type="text" name="text1" value="" id="number1"  /> <br/>
        <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>


Solution

  • You are always calling the value of input with id="op1", which is + in your case. Why not pass the value?

        getResult(id) {
          var result1 = document.getElementById("number1").value;
          var result3 = document.getElementById (id).value;
          var result2 = document.getElementById("number2").value;
          calculate (result1,result3,result2);}
    

    The id is passed when calling the function:

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

    Calculate button won't work this way, but this is a quick fix with your setup. Good luck.