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"

2
  • @Jahnux73 it's better to use parseInt() to preserve data integrity. Commented Oct 30, 2013 at 12:38
  • 1 + 2 may equal 3, but '1' + '2' equals '12'. Commented Oct 30, 2013 at 12:38

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to specify the radix! parseInt(x, 10);
@RGraham Mentioned that in an edit :)
2

For more accuracy:

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

Comments

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);

Comments

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);
        }

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.