I'll preface this with sorry, I'm a complete noob and I just don't understand what is happening.
I'm adding two variables of type number (I checked), and when I print the outcome, I get NaN. :(
More context: I want to add an existing number on my page (3, in the HTML here) to whatever the user inputs, in real time. I can retrieve these numbers fine, and when I check their types, it returns "number". But when I assign a variable to their sum I get NaN. I feel like I'm missing something stupid.
The javascript:
window.onload = setupHandlers;
function getBanana() {
console.log("hi getBAnana is running")
var quantity = document.getElementById("Banana");
var howmany = 0;
if(quantity.value!="") {
howmany = parseInt(quantity.value);
}
console.log(howmany);
var total = document.getElementById("total").innerHTML;
console.log(total);
oldtotal = parseInt(total.value);
console.log("oldtotal type: " + typeof oldtotal);
console.log("howmany: " + howmany);
console.log("howmany type: " + typeof howmany);
newtotal = oldtotal + howmany;
console.log("newtotal type: " + typeof newtotal);
console.log(newtotal);
}
function setupHandlers(){
var Banana = document.getElementById("Banana");
Banana.onchange = getBanana;
}
The HTML:
<!-- some form code and other tags here blabla-->
<input type="number" id="Banana" min="0" placeholder="lbs">
<span id= "total">3</span>
<script src="jstest.js" type="text/javascript"></script>
Any help would be greatly appreciated.
total is a string. Strings do not have .value, so total.value is undefined. parseInt(undefined) is NaN, which is a number even though it is not a number (JavaScript is full of old warts). When you add NaN and any other number, you still get a NaN.
You need parseInt(total).
Also, since 3 is not HTML, it would be better to use .textContent and not .innerHTML.
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