how to sum two numbers from input tag? [duplicate]

Use parseInt(), or parseFloat(); the problem you were experiencing is that you were concatenating two strings, not adding two numbers. parseInt() (assuming that it finds a real number) addresses that issue by converting the string to a number:

 function sum() 
{ 
    var fn, ln, result; 
    fn = parseInt(document.getElementById("n1").value, 10);
    ln = parseInt(document.getElementById("n2").value, 10);
    result =  (fn+ln); 
    document.getElementById("demo2").innerHTML = result; 
}

The , 10 that appears after the value is the radix, which ensures which number-base the returned number (if any) will be.

Also note that the result variable should be declared within the function as well, to avoid polluting the global scope (and possibly creating problems with other variables elsewhere).

References:

Leave a Comment