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;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With