I have built a super simple tip calculator to help me try and get a hold of the javascript knowledge I've gained. I just wanted to see if there was any feedback I could get for it...
Basic functionality is: If a letter or incorrect character is input in either the bill or the number of persons input, a message should appear at the bottom advising this.
Otherwise if everything is okay, the tip per person is shown at the bottom, followed by the total cost per person!
Here is the JS:
const button = document.querySelector('button'),
bill = document.querySelector('#amount'),
serviceRating = document.querySelector('#service'),
numberPersons = document.querySelector('#people'),
pTip = document.querySelector('.tip'),
pTotal = document.querySelector('.total'),
p = document.querySelectorAll('p'),
regex = /(^0|[a-zA-Z]+)/i;
let tipAmount = 0,
totalCostPP = 0;
button.addEventListener('click', () => {
if (regex.test(bill.value)) {
pTip.textContent = 'Please give a valid bill value'
} else if (regex.test(numberPersons.value)) {
pTip.textContent = 'Please enter how many people were there'
} else {
tipAmountPP = tipPP(bill.value, serviceRating.value, numberPersons.value);
totalCostPP = totalPP(tipAmountPP, bill.value, numberPersons.value);
for (paragraph of p) {
paragraph.classList.toggle('hidden');
}
pTip.textContent = `Tip per person: $${tipAmountPP.toFixed(2)}`;
pTotal.textContent = `Total per person: $${totalCostPP.toFixed(2)}`;
}
});
const tipPP = (bill, service, people) => {
let tip = (bill / 100) * service;
return (tip / people);
}
const totalPP = (tip, bill, people) => {
return (bill / people + tip);
}
I haven't included the HTML and CSS as I didn't see it necessary as everything is functioning with each other just now.
Anyway, appreciate any help you can give, little or large!