Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Javascript: adding 2 numbers

Tags:

javascript

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;
    }
like image 504
Alexander Raven Avatar asked Apr 14 '26 08:04

Alexander Raven


1 Answers

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>
like image 151
Nina Scholz Avatar answered Apr 16 '26 23:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!