-1

I'm trying to write a simple calculator by html and JavaScript, however the result of 2+2 is not 4 but 22, please help me with this problem! Thanks!

<html>
<body>
<input type ="text" id ="x">
<p> + </p>
<input type ="text" id ="y"> 

<script>
function adder(a,b){

var x = document.getElementById("x").value;
var y = document.getElementById("y").value;

document.getElementById("demo").innerHTML =  x+y;


}

</script>

<button type = "button" onclick = "adder(x,y)"> calculate </button>

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

</body>
</html>
Yufei Liu
  • 21
  • 1
  • 5

2 Answers2

1

You are not adding numbers but strings, which means concatenation.

Convert them to numbers first:

<html>
<body>
<input type ="text" id ="x">
<p> + </p>
<input type ="text" id ="y"> 

<script>
function adder(a,b){
  var x = Number(document.getElementById("x").value);
  var y = Number(document.getElementById("y").value);

  document.getElementById("demo").innerHTML =  x+y;
}
</script>
<button type = "button" onclick = "adder(x,y)"> calculate </button>
<p id = "demo"> </p>
</body>
</html>

Note this does not include error handling in case the input cannot be converted to a number.

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33
  • I thought .value already set it to a number. So what does .value mean? – Yufei Liu Aug 18 '16 at 00:34
  • @YufeiLiu 'HTMLInputElement.value is a DOMString representing the current value of the control. Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an , the returned value might be an empty string instead.' The note already hints at how to limit the possible inputs. See [HTMLInputElement](https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement) – ASDFGerte Aug 18 '16 at 00:42
  • Thank you so much! – Yufei Liu Aug 18 '16 at 00:51
0

Slightly adding to ASDFGerte's answer you need to convert the elements x and y to integers because get element by id returns a string to do this you can use the parseint function

var x = parseInt(document.getElementById("x").value);
var y = parseInt(document.getElementById("y").value);
Hamish
  • 84
  • 6