0

The following doesn't work as expected:

function sum(x,y){
    return x + y;
}

document.getElementById('submit').onclick = function(e)
{

    //do someting
    e.stopPropagation();

    var value1 = document.getElementById('v1').value,
    value2 = document.getElementById('v2').value;

    var newSum = sum(value1, value2);
    console.log(newSum);

}

There is something wrong with the values being picked up. It should return the sum and not "1+2=12"

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
Aessandro
  • 5,517
  • 21
  • 66
  • 139

4 Answers4

6

Change

return x + y;

to

return parseInt(x) + parseInt(y);

You have to convert the values to numbers first, before adding them. If the numbers are floats, you can use parseFloat instead of parseInt.

Edit As suggested by RGraham in the comments, its always better to pass the radix (check parseInt's doc) explicitly. So, the code becomes

return parseInt(x, 10) + parseInt(y, 10);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

For more accuracy:

  function sum(x,y){    
     return parseFloat(x) + parseFloat(y);
  }
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
2

You need to parse your value to an int as all values are passed as string in javascript.

value1 = parseInt(document.getElementById('v1').value, 10);
value2 = parseInt(document.getElementById('v2').value, 10);
Akshay
  • 350
  • 1
  • 7
1

use

parseInt

Syntax

var num = parseInt(string, radix);

Parameters

string The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.

radix An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

  function sum(x,y){

           return parseInt(x,10) + parseInt(y,10);
        }
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91