Help With JavaScript Tip Calculator

Hey guys,
So I build a tip calculator. The only issue is that it only calculates once. When I click the “calculate” button again, it return NaN. It’ll work again if I refresh the page, but only once. Any ideas why?

Here is my code:

let costOfMeal = document.getElementById('cost-of-meal');
let tipPercent = document.getElementById('tip-percent');
let totalAmount = document.getElementById('total-amount');
let calculate = document.getElementById('calculate');

calculate.addEventListener('click', function() {
    costOfMeal = Number(costOfMeal.value);
    tipPercent = Number(tipPercent.value);

    let totalAmount = (tipPercent/100)*(costOfMeal) + (costOfMeal);


    document.getElementById('total-amount').innerHTML = "$" + totalAmount;

});

Thanks!

First of all, you define totalAmount on the top of the file, then once again inisde the function, you should rename those variables

Hello!

The reason you get NaN is context.

Here:

let costOfMeal = document.getElementById('cost-of-meal');
let tipPercent = document.getElementById('tip-percent');

You store a reference to the DOM element to their variables, which is fine. Then, the first time you click on the calculate button it works nice, but there’s a side effect you’re not taking into account here:

// Inside your calculate click handler
costOfMeal = Number(costOfMeal.value);
tipPercent = Number(tipPercent.value);

See the problem?

Hint

Log (using console.log) the values of costOfMeal and tipPercent before and after the calculation.

I take it the first four variables are form elements (inputs) on the page. I’d set this as constants, for one.

The code inside the functions should use the value of those inputs , not set them. Probably by creating temporary variables for clarity.

For example, inside the function:
let cost = costOfMeal.value;
let percent = tipPercent.value;
(these are temporary variables to hold the user responses in the form)

let totalBill = cost * percent;
(the calculation)

totalAmount.innerHTML = totalBill;
(this takes the result of the calculation and puts it on the page)

–just one way to do it.

2 Likes

Thank you! Your solution worked! Appreciate it!