1

I'm trying to code a calculator where the user inputs two numbers and then selects an operation(+,-,/,*) to perform which should give them a result. I've run the code multiply times in glitch and I keep getting an error in my JS saying 'operation is not defined'(referring to the if statement in the JS). Could anyone explain what I'm doing wrong here and what needs changing

HTML

<html lang="en">
  <head>
    <title>CALCULATOR</title>

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css" />

  </head>
  <body>
    <h1>Calculator</h1>


    First Number : <input type="numbers" id="fnum" /><br /><br />
    Second Number : <input type="numbers" id="snum" /><br /><br />

    Operation? :
    <select id="operation">
      <option value="add">+</option>
      <option value="subtract">-</option>
      <option value="divide">/</option>
      <option value="multiply">*</option> </select><br /><br />

    <input type="button" id="Submit" value="Calculate" onclick="calculate()" />

    <script src="script.js"></script>
  </body>
</html>

JS


  var num1 = parseInt(document.getElementById("fnum").value);
  var num2 = parseInt(document.getElementById("snum").value);

  if (operation == 1) {
    var answer = num1 + num2;
    return answer;
  }
  else if (operation == 2) {
    var answer = num1 - num2;
    return answer;
  }
  else if (operation == 3) {
    var answer = num1 / num2;
    return answer;
  }
  else {
    var answer = num1 * num2;
    return answer;
  }

}
UpUp
  • 31
  • 5
  • 2
    I don't see `operation` declared anywhere. – jmargolisvt May 06 '20 at 14:55
  • Does this answer your question? [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Matt Ellen May 06 '20 at 15:03

1 Answers1

1

You have not declared the operation variable in your js file. Add the following code to the js file:

var o= document.getElementById("#operation") 
var operation = o.options[o.selectedIndex].value

#if-else conditions