How do I sum two numbers from an input tag?

Possible duplicate:
How do I add two lines as if they were numbers?

I wrote some simple JavaScript code and I want to use two input fields and add numbers from two values. Here is the code and I see a result of 1520 instead of 35.

How can I fix this?

n1 <input type = "number" id = "n1" value=15 />
n2 <input type = "number" id = "n2" value=20 />

<p>Sum?</p>
<button onclick="sum()">Try it</button>
<p id="demo2">Result?? </p>

<script type="text/javascript">
 function sum() 
{ 
    var fn, ln; 
    fn = document.getElementById("n1").value; 
    ln = document.getElementById("n2").value; 
    result =  (fn+ln); 
    document.getElementById("demo2").innerHTML = result; 
}
</script>

      

+1


source to share


2 answers


Use parseInt()

or parseFloat()

; the problem you are facing is that you are concatenating two strings without adding two numbers. parseInt()

(assuming it finds a real number) addresses, which are given by converting a 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; 
}

      

, 10

that appears after value

is the base that guarantees which license base will be returned (if any).



Also note that the variable result

must also be declared inside this function, so as not to pollute the global scope (and possibly create problems with other variables elsewhere).

Literature:

+5


source


result =  (parseFloat(fn)+parseFloat(ln)); 

      



+4


source







All Articles