0

Here is my code:

<!DOCTYPE html>
<html>
<header></header>

<body>
  <label id="FirstNumber">First Number:</label>
  <input type="text" id="number1">
  <br>
  <label id="SecondNumber">Second Number:</label>
  <input type="text" id="number2">
  <br>
  <button id="add" onclick="add()">Add</button>
  <button id="multiply" onclick="multiply()">Multiply</button>
  <br>
  <label id="FinalNumberLabel">Answer:</label>
  <label id="Answer"></label>
  <script type="text/javascript">
    function add() {
      var num1 = document.getElementById("number1");
      var num2 = document.getElementById("number2");
      var answer = num1 + num2;
      document.getElementById("Answer").innerHTML = answer;
    }

    function multiply() {
      var num1 = document.getElementById("number1");
      var num2 = document.getElementById("number2");
      var answer = num1 * num2;
      document.getElementById("Answer").innerHTML = answer;
    }
  </script>
</body>

</html>

The "Multiply" button returns a "NaN" error and the Add button always returns "[objectHTMLInputElement][objectHTMLInputElement]"

Why doesn't this work?

1
  • Calculating with element objects might be hard. Use their values converted to numbers instead. Commented Jan 29, 2016 at 15:51

2 Answers 2

2

You're not getting the values, just the elements:

var num1 = document.getElementById("number1");

In this case num1 isn't actually a number, it's an objectHTMLInputElement.

You probably want to start with something like:

var num1 = parseFloat(document.getElementById("number1").value);

Perhaps also add some error checking, or specify that the inputs need to be numeric, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that really helps!
0
  1. .value -> you do not want the input element, you want the value it holds

  2. parseInt -> you want number not string (or parseFloat if you want floats)

    function add() {
      var num1 = parseInt(document.getElementById("number1").value);
      var num2 = parseInt(document.getElementById("number2").value);
      var answer = num1 + num2;
      document.getElementById("Answer").innerHTML = answer;
    }
    
    function multiply() {
      var num1 = parseInt(document.getElementById("number1").value);
      var num2 = parseInt(document.getElementById("number2").value);
      var answer = num1 * num2;
      document.getElementById("Answer").innerHTML = answer;
    }
    

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.