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.
You need to listen for an event on the input element (
inputgenerally), and once that event happens, check the value.
- You can’t redeclare a variable in the same scope - you use
lettwice in both functions. You should declare with
let, then mutate that, like
let foo = 1; foo += 1;(note the lack of a
leton the second one).
- The second function is a problem as well -
tipPercentdon’t exist in the scope of the
calculateTotalfunction, you need to either pass them in or just move the code in that function into the
- You also need to convert the values to actual numbers: when you get them from the DOM, they are strings.
- You’ll want to set the
valuefor 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.
- 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.