Tip & Bill Splitter
60 minBeginnerHTML formsJavaScriptEventsValidation
Outcome
A working form that shows “Tip per person” and “Total per person” in RM with two decimals, refuses bad input with a friendly message, and resets cleanly.
Learning objectives
- ▸Build an accessible form with
<label for>and number inputs - ▸Handle the form's
submitevent and stop the page reload withpreventDefault() - ▸Convert input text to numbers and format money with
toFixed(2) - ▸Validate input and show helpful error messages instead of
NaN
Prerequisites
- •Basic HTML (elements and attributes) — see the HTML & CSS track
- •Beginner JavaScript: variables, functions,
ifstatements anddocument.querySelector— see the JavaScript track
Expected behaviour
- ✓Entering bill RM 100, tip 10% and 2 people, then pressing Calculate shows RM 5.00 tip and RM 55.00 total per person.
- ✓Amounts always have exactly two decimals (RM 38.33, never 38.333333).
- ✓An empty bill, a negative tip or 0 / 2.5 people shows a clear error message — never
NaNorInfinity. - ✓The Reset button clears the inputs, the results and any error.
Eating out with friends and splitting the bill is a perfect first JavaScript app: a few inputs, one calculation, and lots of ways for users to type something unexpected. Tipping is optional in Malaysia (many restaurants already add a service charge), so set the tip to 0% and this works as a plain bill splitter too.
tip = bill × (tip% ÷ 100)
tipPerPerson = tip ÷ people
totalPerPerson = (bill + tip) ÷ peopleThe whole calculation. The real work is getting clean numbers into it.
submit event on the form. Your code listens for it.Input values are always strings, even in type="number" inputs. "100" + 10 is "10010", not 110 — so convert with Number() first.
Milestones
In index.html, replace the comment with:
• a <form id="tip-form"> containing three number inputs: #bill, #tip and #people, each with a matching <label for="…">
• a <p id="error"> for error messages (empty for now)
• a submit button (<button type="submit">Calculate</button>)
• after the form, two result elements: #tip-per-person and #total-per-person (start them at RM 0.00)
The CSS is already written for these ids and classes, so it should look good immediately.
Checks
- There's a
form#tip-form #bill,#tipand#peopleare number inputs in the form- Every input has a label
- The form has a submit button
- Error box and both result elements exist
Console output from your code appears here.