Alexander Raven Alexander Raven - 27 days ago 16
Javascript Question

Learning Javascript: adding 2 numbers

I am learning javascript and trying to complete a simple excercise: add 2 numbers that are entered in 2 separate entry field and show the sum on a page. The script below is executed when you press a button. The problem I'm somehow unable to solve is that the result of the addition is always zero. What I am doing wrong here?

var inputA = document.getElementById("numberA");
var convertA = +inputA;
var inputB = document.getElementById("numberB");
var convertB = +inputB;

function myFunction() {
document.getElementById("result").innerHTML = convertA + convertB;
}

Answer

You need to take the value of the text input .

var inputA = document.getElementById("numberA").value;
//                                             ^^^^^^ 

Please move the variables inside into the function, because the value property returns a string and not a referece to the object.

function myFunction() {
    var inputA = document.getElementById("numberA").value; 
    var inputB = document.getElementById("numberB").value;
    var convertA = +inputA;
    var convertB = +inputB;
    document.getElementById("result").innerHTML = convertA + convertB;
}
<input id="numberA" type="text">
<input id="numberB" type="text">
<button onclick="myFunction()">calc</button>
<div id="result"></div>

Comments