Skip to content
WANCODE
BM

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 submit event and stop the page reload with preventDefault()
  • 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, if statements and document.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 NaN or Infinity.
  • 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.

JavaScript
tip            = bill × (tip% ÷ 100)
tipPerPerson   = tip ÷ people
totalPerPerson = (bill + tip) ÷ people

The whole calculation. The real work is getting clean numbers into it.

Pressing the button fires a 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, #tip and #people are number inputs in the form
  • Every input has a label
  • The form has a submit button
  • Error box and both result elements exist
Completion checklist

Tick these when they're true for your project. The project completes when every milestone passes and every item is ticked.

Preview

Console output from your code appears here.

Step 1 of 5