Tip calculator not working

Tip calculator not working


Can someone help me understand why tipAmount and billTotal aren’t being passed to the forms?



You need to look at your browser’s console (Ctrl+Shft+J in Chrome) and you will see you have a syntax error on line 5 of your script.js file. When you fix that, you will have another syntax error show on line 13 of your script.js file.


EDIT: missed the inline event handler

Interacting with input elements, pushing buttons etc, is asynchronous.

When you run that script, it will get the values immediately, of whatever the initial value is. For example if you change one of the inputs to <input type="text" value="100" id="billAmount" placeholder="Enter bill amount here">, you’d be able to see the JS grab a value of 100.

  1. You need to listen for an event on the input element (change or input generally), and once that event happens, check the value.
  2. You can’t redeclare a variable in the same scope - you use let twice in both functions. You should declare with let, then mutate that, like let foo = 1; foo += 1; (note the lack of a let on the second one).
  3. The second function is a problem as well - billAmount and tipPercent don’t exist in the scope of the calculateTotal function, you need to either pass them in or just move the code in that function into the calculateTip function.
  4. You also need to convert the values to actual numbers: when you get them from the DOM, they are strings.
  5. You’ll want to set the value for the elements to 0 in the HTML so you always have a numeric value rather than an empty string: at the minute, it’ll try and do calculations against an empty string, which is not possible.
  6. Setting a value in the DOM is a side effect: return document.getElementById("tipAmount").value = tipAmount; will return and exit the function, so the second part of the calculation will never get reached anyway - should just be document.getElementById("tipAmount").value = tipAmount;.


The OP’s HTML file has an onchange=“calculateTip()” attached to the input with id=“tipPercent”.


Ach, I missed that. I just tend to assume no inline event handlers, is a bad [or good?] habit, editing original post


It is the duplicate “let” which seems to be part of the problem. The HTML does not have an onchange=“calculateTip()” for the bill amount, which should be something to consider, but would need some logic for handling the blank tipPercent field (your point #6 above).


Yeah, that’s a basic syntax error.

Oh hell, + the return will exit the function as well, so even if it is adjusted as long as it returns it will never actually reach that code, so the "don’t use return" point is not minor


Thanks for your help, it works perfectly now.