-2

I'm trying to do a simple calculator. Here's what I've got:

<script>
  function f1() {
    var x = document.getElementById("num1");
    var y = document.getElementById("num2");
    var z = x + y;
    alert(z);
  }
</script>


<input id="num1" type="text">
<input id="num2" type="text">
<button onclick="f1()">Click</button>

I keep getting an error.

vhu
  • 12,244
  • 11
  • 38
  • 48
João
  • 67
  • 1
  • 7
  • What error? [There's nothing causing errors in your code](http://jsfiddle.net/9phab0Ln/). – Teemu Sep 13 '15 at 18:14

2 Answers2

0

You need to extract the values of those inputs.

function f1() {
    var x = document.getElementById("num1").value;
    var y = document.getElementById("num2").value;
    var z = x + y;
    alert(z);
  }

for detail see here.

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

x and y are both HTMLElements, not Numbers, so you can't simply add them together. Instead, you want to add their value properties together after you've converted them to Numbers:

var z = parseFloat(x.value) + parseFloat(y.value);

MDN has a good article on JavaScript types that might be helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

Dan Nichols
  • 469
  • 2
  • 5