Tip calculator not working

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

https://github.com/qtrandeveloper/tipcalculator/blob/master/script.js

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;.

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

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

1 Like

Thanks for your help, it works perfectly now.