{module 5}
Events and decisions
Your first JavaScript20 min read
What you will be able to do
- Run code when a visitor clicks a button, types in a field or sends a form.
- Make a decision in a script with
if,elseand comparisons. - Show a message beside the field that is wrong, and remove it when the field is right.
Why it matters
Hanok Stay is a guesthouse in a traditional house in Jeonju, South Korea. Each room sleeps up to four guests. Min-seo, the owner, had a page where visitors worked out the price of a stay. One evening a family of seven arrived with a printed price for one room. The page had worked it out without a word of warning. Min-seo had no second room free, and spent an hour finding them beds in another guesthouse.
A calculator that accepts every number gives prices for things that cannot happen: seven guests in one room, or zero nights. A page must decide what it accepts, and say clearly when something is wrong.
The idea
Three events
In lesson 1 the page listened for input. It can listen for other events in the same way:
inputhappens on a field every time its value changes.clickhappens on a button when it is clicked, tapped, or pressed with the keyboard.submithappens on aformwhen it is sent. A visitor sends a form by clicking its submit button or by pressing Enter in one of its fields. Either way, the form gets onesubmitevent, so you listen on theformelement.
form.addEventListener("submit", showPrice);
guestsField.addEventListener("input", clearResult);
nightsField.addEventListener("input", clearResult);
startAgain.addEventListener("click", clearForm);The browser's own action
In module 2 you learned that a form needs a program to receive it. When a form is sent, the browser loads a new page and sends the fields with it. This form names no program, so the browser loads the same page again, and everything the script wrote disappears.
When the browser runs a listener, it gives it one value: an object describing the event, usually named event. event.preventDefault() tells the browser not to take its own action:
function showPrice(event) {
event.preventDefault();Call it first in every submit listener.
The form element in this lesson also has the attribute novalidate. It turns off the checks the browser makes by itself, which you saw in module 2, because this script checks the fields and writes its own messages.
Comparisons
A comparison asks a question about two values and answers with a boolean, true or false.
===asks "is equal to".guestsMessage === ""istruewhen the message is empty.!==asks "is not equal to".<,>,<=and>=ask "less than", "greater than", "less than or equal to" and "greater than or equal to".
Do not confuse === with =. One = sets a variable to a value. Three ask whether two values are equal.
Number.isInteger() asks whether a value is a whole number. Number.isInteger(3) is true. For 2.5, and for NaN, it is false.
Two questions can be joined. || means "or": the whole question is true when at least one part is true. && means "and": it is true only when both parts are.
if and else
if runs a block of code only when a comparison is true. else if asks another question when the first answer was false, and else runs when every answer was false:
function guestsProblem(guests) {
if (Number.isInteger(guests) === false || guests < 1) {
return `Enter the number of guests, from 1 to ${maxGuests}.`;
} else if (guests > maxGuests) {
return `A room sleeps at most ${maxGuests} guests. For a larger group, book two rooms.`;
} else {
return "";
}
}If the number is not whole, or is below 1, the function returns the first message. Otherwise, if it is above 4, it returns the second. Otherwise it returns an empty string. Only one of the three blocks runs.
An empty field becomes 0 with Number(), as you saw in lesson 2. 0 is below 1, so an empty field gets the first message. That is the fix the order page in lesson 2 needed.
A message beside the field
A useful message appears next to its field and says what to type. In the HTML, each field has an empty paragraph under it for its message. The aria-describedby attribute of each field holds the id of that paragraph, so that a screen reader reads the message together with the field.
The script writes the message, or the empty string, into that paragraph every time the form is sent. Writing the empty string is what removes an old message.
Worked example
Create index.html, styles.css and booking.js in a new folder and save them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Price of a stay, Hanok Stay</title>
<link rel="stylesheet" href="styles.css" />
<script src="booking.js" defer></script>
</head>
<body>
<main>
<h1>Hanok Stay</h1>
<p>A room costs $70 a night and sleeps up to 4 guests. We take stays of 1 to 14 nights.</p>
<form id="booking" novalidate>
<p>
<label for="guests">Guests</label>
<input type="number" id="guests" name="guests" aria-describedby="guests-error" />
</p>
<p class="error" id="guests-error"></p>
<p>
<label for="nights">Nights</label>
<input type="number" id="nights" name="nights" aria-describedby="nights-error" />
</p>
<p class="error" id="nights-error"></p>
<button type="submit">Show the price</button>
<button type="button" id="start-again">Start again</button>
</form>
<p id="result"></p>
</main>
</body>
</html>body {
max-width: 40rem;
margin: 0 auto;
padding: 1rem;
font-family: Arial, sans-serif;
line-height: 1.5;
}
.error {
margin: 0;
color: #a11212;
}
#result {
font-weight: bold;
}const nightCents = 7000;
const maxGuests = 4;
const maxNights = 14;
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const form = document.querySelector("#booking");
const guestsField = document.querySelector("#guests");
const nightsField = document.querySelector("#nights");
const guestsError = document.querySelector("#guests-error");
const nightsError = document.querySelector("#nights-error");
const result = document.querySelector("#result");
const startAgain = document.querySelector("#start-again");
function guestsProblem(guests) {
if (Number.isInteger(guests) === false || guests < 1) {
return `Enter the number of guests, from 1 to ${maxGuests}.`;
} else if (guests > maxGuests) {
return `A room sleeps at most ${maxGuests} guests. For a larger group, book two rooms.`;
} else {
return "";
}
}
function nightsProblem(nights) {
if (Number.isInteger(nights) === false || nights < 1 || nights > maxNights) {
return `Enter the number of nights, from 1 to ${maxNights}.`;
} else {
return "";
}
}
function showPrice(event) {
event.preventDefault();
const guests = Number(guestsField.value);
const nights = Number(nightsField.value);
const guestsMessage = guestsProblem(guests);
const nightsMessage = nightsProblem(nights);
guestsError.textContent = guestsMessage;
nightsError.textContent = nightsMessage;
if (guestsMessage === "" && nightsMessage === "") {
result.textContent = `Guests: ${guests}. Nights: ${nights}. Price: ${dollars.format((nights * nightCents) / 100)}`;
} else {
result.textContent = "";
}
}
function clearResult() {
result.textContent = "";
}
function clearForm() {
guestsField.value = "";
nightsField.value = "";
guestsError.textContent = "";
nightsError.textContent = "";
result.textContent = "";
}
form.addEventListener("submit", showPrice);
guestsField.addEventListener("input", clearResult);
nightsField.addEventListener("input", clearResult);
startAgain.addEventListener("click", clearForm);Open the page, type 2 guests and 3 nights, and click "Show the price":
Guests: 2. Nights: 3. Price: $210.00Click "Start again" and then "Show the price" with both fields empty. A message appears under each field:
Enter the number of guests, from 1 to 4.
Enter the number of nights, from 1 to 14.Type 6 guests and 2.5 nights, and press Enter in the nights field:
A room sleeps at most 4 guests. For a larger group, book two rooms.
Enter the number of nights, from 1 to 14.Try the largest stay the rules allow, 4 guests and 14 nights:
Guests: 4. Nights: 14. Price: $980.00Read booking.js from the top. Lines 1 to 3 hold the rules. The messages are template literals that use them, so a change to maxGuests changes the messages too. Lines 14 to 30 are two functions that each check one field and return a message.
showPrice, from line 32, stops the reload, reads both fields, asks for both messages and writes them beside the fields. Only when both are empty does it show a price.
clearResult runs whenever either field changes, so the page never shows a price for numbers that are no longer in the fields. clearForm empties everything when "Start again" is clicked. That button has type="button", so it does not send the form.
Common mistakes
Forgetting preventDefault
Remove line 33, event.preventDefault();, and the event in the brackets above it. Type 9 guests and 3 nights, and press Enter. For a moment the message appears. Then it is gone, and both fields are empty. The address bar now ends like this:
file:///home/you/project/no-prevent.html?guests=9&nights=3The listener ran. Then the browser loaded the page again, with the fields added to the address after a ?. When a page forgets everything after a form is sent, look for that ?. Put event.preventDefault() back.
A message that never goes away
In this version, the messages are written only when there is a problem:
if (guestsMessage !== "") {
guestsError.textContent = guestsMessage;
}Type 9 guests and 3 nights and send. Then change the guests to 2 and send again:
A room sleeps at most 4 guests. For a larger group, book two rooms.
Guests: 2. Nights: 3. Price: $210.00There is no error, but the page now contradicts itself: a warning and a price for the same booking. Nothing ever removes the old message. Write to the message paragraph every time: the problem, or the empty string.
One = where you meant ===
if (guestsMessage = "" && nightsMessage === "") {Type 2 and 3 and send. No price appears, and the Console shows:
page error: Uncaught TypeError: Assignment to constant variable.You saw this message in lesson 2. One = tries to set guestsMessage, which is a const. Use === to compare.
Think it through
Wanjiru runs a page for a cooking class with 10 places. She wants a field for the number of places and a message: "Only 10 places. Choose 1 to 10." when the number is wrong.
Understand. In: one number field. Out: either a message beside the field, or a confirmation line. Wrong means empty, below 1, above 10, or not whole.
Break down. Read the field and turn it into a number. Decide whether it is wrong. Write the message or the empty string. Show the confirmation only when there is no message.
Plan. A function placesProblem(places) with one if and an else, joined with ||. A submit listener that starts with event.preventDefault().
Build. She writes placesProblem first and tests it with console.log(placesProblem(0), placesProblem(4)). The Console shows her message, then an empty string, which looks like nothing at all. Then she connects the listener.
Test. 4 shows the confirmation. 0, 11 and an empty field show the message. The odd case is 10, the limit itself, which must pass. She had written places >= 10 and it failed, so she changed it to places > 10.
Reflect. The limit was where her mistake was. From now on she tests the exact limit first, then one on each side.
At work
A README that lists only what works misleads the next person, who finds the gaps later, often in front of a customer. A section called "Known problems" tells them first, in plain words, without excuses.
Do-yun, Min-seo's son, built the page. His README ends like this:
Known problems
- The page does not know which nights are already booked. It shows a price, not whether a room is free.
- It prices one room. A group of five or more is told to book two rooms, but the page cannot price two rooms together.
- Nothing is sent to Hanok Stay. The visitor still has to send a message to book.
Each line says what does not work and what it means for a guest. None says "should" or "hopefully". The next person can decide which problem to fix first.
Your tasks
Task 1: Build the booking page
Create the three files and try the four cases from the worked example. Then use only the keyboard: Tab to each field, type, and press Enter.
You are done when all four outputs match, and you can send the form and click "Start again" without the mouse.
Task 2: Break it twice
Remove event.preventDefault(), send the form, and look at the address bar. Put it back. Then change the else in showPrice so that it no longer empties the result, and find a way to make the page show a price and a message at the same time.
You are done when you have seen the ?guests= address and the double message on your own page, and both are fixed.
Task 3: Breakfast for some guests
Add a number field, "Guests who want breakfast", at $9 per guest per night. It cannot be more than the number of guests, and it can be 0. Show a message beside it when it is wrong, and add the breakfast to the price.
You are done when 2 guests, 3 nights and 1 breakfast show $237.00, and 3 breakfasts for 2 guests show your message and no price.
Recap
click,inputandsubmitare events. Listen forsubmiton the form, not on the button.event.preventDefault()stops the browser from reloading the page when a form is sent.- Comparisons give
trueorfalse.===compares, and one=sets a variable. if,else ifandelsechoose one block to run.||means "or", and&&means "and".- Write each field's message, or the empty string, beside it every time you check.
Go deeper
- MDN: Introduction to events covers listeners and the event object at the level of this lesson.
- MDN: Event.preventDefault() explains what it stops and when it has no effect.
- MDN: if...else is the reference page, with
else if. - MDN: Number.isInteger() lists what counts as a whole number.