why does innerHTML return number as NaN?

here's my code:
const bill = document.getElementById('bill');
const billAmount = parseFloat(bill.value);
const numOfPeople = document.getElementById('numberOfPeople');
const numberOfPeople = parseFloat(numOfPeople.value);

let tipAmount = document.querySelector('.tip_amount');

tipButtons.forEach(tipButton => {
tipButton.addEventListener('click', (e) => {
if(e.target.innerText === "5%") {
console.log("calculate 5% tip")

tipAmount.innerHTML = (billAmount * 0.05) / numberOfPeople;
}
})
});
const bill = document.getElementById('bill');
const billAmount = parseFloat(bill.value);
const numOfPeople = document.getElementById('numberOfPeople');
const numberOfPeople = parseFloat(numOfPeople.value);

let tipAmount = document.querySelector('.tip_amount');

tipButtons.forEach(tipButton => {
tipButton.addEventListener('click', (e) => {
if(e.target.innerText === "5%") {
console.log("calculate 5% tip")

tipAmount.innerHTML = (billAmount * 0.05) / numberOfPeople;
}
})
});
11 Replies
Jochem
Jochem2y ago
likely either billAmount or numberOfPeople is NaN, but without the HTML to go along with this (preferably in a codepen) it's impossible to tell for sure
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Jochem
Jochem2y ago
shouldn't be necessary, the event handler is a closure so it should have the outer state wrapped up inside wait, no, you're right nm, I was thinking of getting the elements, you're absolutely 100% correct the parsefloats need to be in the listener
MarkBoots
MarkBoots2y ago
also maybe its an idea to use radio buttons instead (inside a form and grouped by name). then you can use a single change or input event on the form as example https://codepen.io/MarkBoots/pen/MWBWMpV?editors=1111
winniffy
winniffy2y ago
this works. but is there a reason why it doesn't work outside the eventlistener? i dont quite get it. moreso because the codepen link appears broken so i dont see what you mean cheers guys
MarkBoots
MarkBoots2y ago
i restored the codepen, you can check what i mean
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
winniffy
winniffy2y ago
thanks alot, i get it now
MarkBoots
MarkBoots2y ago
make sure you fork the pen for if you need it later. i might delete it again
winniffy
winniffy2y ago
makes sense
MarkBoots
MarkBoots2y ago
pen removed, backup
Want results from more Discord servers?
Add your server