2

I have been teaching myself some Javascript; and I am having trouble getting this function to run properly. This is what is being output.

Answer: [object HTMLInputElement][object HTMLInputElement]

function addNumbers() {
  var firstNum = document.getElementById("num1");
  var secondNum = document.getElementById("num2");
  result = firstNum + secondNum;
  document.getElementById("demo").innerHTML = "Answer: " + result;
  return result;

}
<!DOCTYPE html>
<html>

<head>
  <!--            ,<script src="scripts.js"></script> -->
</head>

<body>

  <h2>JavaScript Functions</h2>

  <p>This example calls a function which performs a calculation and returns the result:</p>


  <form>
    First Number<br>
    <input type="text" name="firstNum" id="num1"><br> Second Number<br>
    <input type="text" name="secondNum" id="num2"><br>
    <input type="button" value="Add!" onclick="addNumbers()">
  </form>

  <p id="demo"></p>
</body>

</html>

5
  • 2
    You're logging the input elements themselves, instead of their values. Try e.g. var firstNum = document.getElementById("num1").value Commented Mar 11, 2019 at 23:27
  • document.getElementById returns a node. If you want the content of it, you'll need to extract the value. Commented Mar 11, 2019 at 23:28
  • Welcome to SO. With document.getElementById("num2") you are selecting the element with id num2 and not it's value. Commented Mar 11, 2019 at 23:28
  • 1
    (Also, you'll need to convert those values into numbers before adding them together -- Number(firstNum) + Number(secondNum) Commented Mar 11, 2019 at 23:29
  • That did it thanks! and also for the values conversion bit, Would have stumbled me next for sure. Commented Mar 11, 2019 at 23:41

1 Answer 1

4

Like the comments said, get the value from the HTML element node and parse it into a float

var firstNum = parseFloat(document.getElementById("num1").value);
var secondNum = parseFloat(document.getElementById("num2").value);

function addNumbers() {
  var firstNum = parseFloat(document.getElementById("num1").value);
  var secondNum = parseFloat(document.getElementById("num2").value);
  result = firstNum + secondNum;
  document.getElementById("demo").innerHTML = "Answer: " + result;
  return result;

}
<!DOCTYPE html>
<html>

<head>
  <!--            ,<script src="scripts.js"></script> -->
</head>

<body>

  <h2>JavaScript Functions</h2>

  <p>This example calls a function which performs a calculation and returns the result:</p>


  <form>
    First Number<br>
    <input type="text" name="firstNum" id="num1"><br> Second Number<br>
    <input type="text" name="secondNum" id="num2"><br>
    <input type="button" value="Add!" onclick="addNumbers()">
  </form>

  <p id="demo"></p>
</body>

</html>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.