GullyBoy GullyBoy - 3 months ago 10
Javascript Question

Simple Addition,Subtraction Javascript Function....Why Does This Not Work?

i am building a simple javascript function and it is not working what am i doing wrong?
here is the code below guys thanks

<p>Simple ADD/SUBTRACT Calculator</p>

<input type="text" id="num1"><br> <!-- field for number 1 -->
<input type="text" id="num2"><br> <!-- field for number 2 -->
Enter ADD or SUBTRACT to calculate<br>
<input type="text" id="opper" value""><br> <!-- field for ADD or SUBTRACT text -->
<button type="submit" onclick="myCalculator(document.GetElementById('num1').value , document.GetElementById('num2').value)">Calculate</button>

<p id="answerspace"></p><!-- field for the answer -->


<script>
function myCalculator(a, b) {
var theOperatr = document.GetElementById('opper').value;

if (theOperatr = "ADD") {
document.GetElementById('answerspace').innerHTML = a + b;
}

else if (theOperatr = "SUBTRACT") {
document.GetElementById('answespace').innerHTML = a - b;
}

else {
document.GetElementById('answerspace').innerHTML = "NOTHING WAS ENTERED";
}

};
</script>

Answer

<p>Simple ADD/SUBTRACT Calculator</p>

<input type="number" id="num1">
<br>
<!-- field for number 1 -->
<input type="number" id="num2">
<br>
<!-- field for number 2 -->
Enter ADD or SUBTRACT to calculate
<br>
<input type="text" id="opper" value "">
<br>
<!-- field for ADD or SUBTRACT text -->
<button type="submit" onclick="calculate()">Calculate</button>

<p id="answerspace"></p>
<!-- field for the answer -->

<script>
  
  function calculate() {

    var num1 = parseInt(document.getElementById('num1').value);
    var num2 = parseInt(document.getElementById('num2').value);

    var operator = document.getElementById('opper').value;

    if (operator === "ADD") {
      document.getElementById('answerspace').innerHTML = num1 + num2;
    } else if (operator === "SUBTRACT") {
      document.getElementById('answerspace').innerHTML = num1 - num2;
    } else {
      document.getElementById('answerspace').innerHTML = "NOTHING WAS ENTERED";
    }
    
  }
  
</script>

document.GetElementById should be document.getElementById.

You should also use input type number for numbers

Due to the way you are calling myCalculator you also needed to call parseInt on the values.

I have altered your code slightly so it's a bit more readable.