0

I am new so thank you for your patience. I did search a lot for the answer but couldn't find, maybe because it's too obvious.

In this case the inputs x and y are taken from <input type="number"..

This function executes upon button click.

Can you tell me why it returns a concatenation, e.g. 33 instead of 6, 45 instead of 9.

  function sum(x,y) {
       x = document.getElementById("x").value;
       y = document.getElementById("y").value;
       var answer = x+y;

       document.getElementById("sum").innerHTML = answer;

  }

Many thanks in advance.

Hex25
  • 1
  • 2
  • Because the values you're getting are strings and you need to cast them to numbers. There has to be a million dupes of this question on SO alone. Looking for one now... – j08691 Jun 21 '17 at 14:40
  • .value always returns a string. So tell JS to interpret it as number by e.g. using ....value * 1 or parseInt, or parseFloat, or... – newBee Jun 21 '17 at 14:41

4 Answers4

3

You need to convert it into number.

function sum(x,y) {
   x = document.getElementById("x").value;
   y = document.getElementById("y").value;
   var answer = Number(x)+Number(y);

   document.getElementById("sum").innerHTML = answer;

}
The_Outsider
  • 1,875
  • 2
  • 24
  • 42
1

Because when you put a string on either side of the + operator, it performs concatenation.

"3" + "3" // "33"

The value property of an input will always give you a string.

Convert the strings to numbers if you want to add them together.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • The value property of an input will always give you a string. - odd when input type is "number", innit. Thank you, that explains the issue! – Hex25 Jun 21 '17 at 15:18
1

This happens beacuse xand y are Strings, to proper operate with them use Number(x) + Number(y) or parseFloat(x) + parseFloat(y)

dloeda
  • 1,516
  • 15
  • 23
0

You want to use the parseInt function to actually convert the strings to ints and then add them like this

function sum(x,y) {
   x = parseInt(document.getElementById("x").value);
   y = parseInt(document.getElementById("y").value);
   var answer = x+y;

   document.getElementById("sum").innerHTML = answer;

}
Colwin
  • 2,655
  • 3
  • 25
  • 25