In the overview, you watched Sam’s finished recipe box take a new recipe, filter the list, and confirm a deletion, all from the keyboard. Every one of those features starts when someone types into a box and your script reads what they typed.
Reading a box sounds like one line of code. However, the browser hands your script text, even from a box made for numbers, and an empty box can pass for a real number. In this lesson, you’ll predict exactly what a script reads from a box, and you’ll write a click handler that converts it, checks it, and responds on the page. Start by setting up the page where Sam’s shopping list begins.
Set Up Sam’s Shopping List
Sam, who played at Priya’s game nights, keeps the family recipes on paper and wants them on a page. Before the recipe box, you’ll build Sam’s weekly shopping list, one control at a time. By the end of the course, you’ll build the recipe box itself, with forms that check what people type and controls that work with a keyboard alone.
This course assumes you know the JavaScript basics and have built a page that reacts to clicks and served it from your own machine. It also assumes you’ve kept a page’s data in an array and drawn the page from it with a render() function, though this first lesson doesn’t need that yet.
Type along with text lessons like this one, and watch the videos for what moves on the page. Each section ends with an exercise you solve in the browser, with tests that check your code.
The shopping list lives in a new folder. Set it up like this:
- Create a folder named
kitchenwith the three files below. - In VS Code, open the folder that holds
kitchen, and start Live Preview onkitchen/index.htmlwith Live Preview: Show Preview (External Browser) from the Command Palette. - In Chrome or Edge, check that the address starts with
http://and ends with/kitchen/index.html. - Open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS.
The page has two labeled boxes, an Add button, two empty lines for the script to fill, and an empty list:
kitchen/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Shopping List</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Sam's Shopping List</h1>
<label>
Item
<input id="item-name">
</label>
<label>
How many?
<input id="item-count" type="number">
</label>
<button id="add-item">Add</button>
<p id="next"></p>
<p id="message"></p>
<ul id="items"></ul>
</main>
<script type="module" src="main.js"></script>
</body>
</html>
The stylesheet colors the line that will hold messages about bad input:
kitchen/style.css
#message {
color: firebrick;
}
The script starts by finding the elements it needs. Its addItem() function draws one list item, such as eggs (3), with createElement(), textContent, and append():
kitchen/main.js
const nameInput = document.querySelector("#item-name");
const countInput = document.querySelector("#item-count");
const addButton = document.querySelector("#add-item");
const nextLine = document.querySelector("#next");
const message = document.querySelector("#message");
const itemList = document.querySelector("#items");
function addItem(name, count) {
const item = document.createElement("li");
item.textContent = `${name} (${count})`;
itemList.append(item);
}
For now, addItem() changes only the page. In a later lesson, you’ll add a full form, keep the items in an array, and draw them with render(), as you did before.
Read the Box When Someone Clicks
Sam types 3 into the How many? box and clicks Add. Your script needs that 3, and it needs it at the moment of the click.
You’ve read a box like this before. On Priya’s guest list, the Add guest handler read the Late guest box with its value property, which holds what’s in the box right now:
const name = lateInput.value.trim();
The item name works the same way. The How many? box is different because of its type="number" attribute. That attribute makes a number box. Chrome won’t let you type most letters into it, and phones display a numeric keyboard.
So what does value give you for a number box? Add this listener to main.js to find out:
kitchen/main.js
addButton.addEventListener("click", () => {
const countText = countInput.value;
console.log("count:", countText, typeof countText);
});
Save, type 3 in How many?, click Add, and look at what the Console shows:
count: 3 string
The last word, string, is the answer. The value is the string "3", not the number 3, and the typeof operator says so. A box’s value is always a string, whatever its type. The type attribute changes how the box behaves.
Next, try something the box can’t read as a number. The letter e is allowed, because 2e3 is a way to write 2000. Clear the box, type 2e, and click Add:
count: string
There are two spaces after count: because the value is an empty string. A number box gives "" for anything it can’t read, so your script never sees the 2e that’s on the screen.
Watch out: if you read the box at the top of main.js, with const count = Number(countInput.value); outside the handler, that line runs only once, while the page loads. The box is still empty then, so count stays 0 no matter what Sam types. Keep the querySelector() lines at the top, and read value inside the handler.
Practice predicting when and what your script reads before you move on. The button below opens a conversation with the AI mentor and asks it to quiz you. The mentor describes what someone types and when your code reads the box. You reply with the value and its type, and the mentor tells you whether you’re right and why.
Convert Once, Then Check
Sam’s list needs a count it can compare and add up, so the handler has to turn the string into a number. It also has to reject input that contains no number at all and say so where Sam will see it.
The Number() function converts a string to a number. Try these in the Console:
> Number("3")
3
> Number("three")
NaN
> Number("")
0
The first two results hold no surprises. NaN, short for “not a number,” is what Number() gives for text it can’t read. The empty string is the one to remember, because it becomes 0 instead of NaN. Therefore, checking for NaN alone would let an empty box through as zero eggs.
To test for NaN, use Number.isNaN(), because NaN === NaN is false. Number.isNaN() only checks the number, though, and the number from an empty box looks fine:
> Number.isNaN(Number("three"))
true
> Number.isNaN(Number(""))
false
So the handler trims the string, checks it for "" first, and then checks the converted number for NaN. With type="number", the empty check catches 2e as well, since the box reads it as "". The trim and the NaN check cost little and keep the handler working correctly if the box ever loses its type attribute and lets through spaces or letters.
The message goes on the page, in the red line. Sam never opens the Console, and a pop-up alert() blocks the whole page until it’s closed. Replace your logging listener with this one:
kitchen/main.js
addButton.addEventListener("click", () => {
const name = nameInput.value.trim();
const countText = countInput.value.trim();
const count = Number(countText);
if (name === "") {
message.textContent = "Type the item's name first.";
} else if (countText === "" || Number.isNaN(count)) {
message.textContent = "Type how many you need, like 3.";
} else {
message.textContent = "";
addItem(name, count);
}
});
The handler reads both boxes once, converts once, and stores the number in count. You call trim() on both values, as you did for the Late guest box, so a box holding only spaces counts as empty. The else branch clears any old message before it adds the item.
Save, and break it on purpose. Click Add with both boxes empty, and the red line says Type the item's name first. Type eggs and 2e, click Add, and it says Type how many you need, like 3. Change the count to 3 and click Add again. The message disappears, and eggs (3) joins the list:
A count of 0 or -2 still gets through, since both are numbers. The browser can check a range for you, and that comes in a later section. That’s all you need about limits for now.
An empty string and a string that can’t be converted to a number often get mixed up, since one gives 0 and the other NaN. This next button opens the AI mentor again, this time with three inputs for How many?. For each input, say whether the empty check or the NaN check catches it, or whether it gets through.
Update a Line as Someone Types
A click tells your script when to read the boxes. Sometimes the page should respond before you click, such as by updating a line that shows what Add is about to put on the list.
The input event fires on a box each time you edit it: when you press a key to add or remove a character, paste text, or click the number box’s arrows. It doesn’t fire when your code assigns to value, as in countInput.value = "". The empty #next line can follow both boxes with one function, showNext(), which reads them as the event fires:
kitchen/main.js
function showNext() {
const name = nameInput.value.trim();
nextLine.textContent = `Next: ${name} (${countInput.value})`;
}
nameInput.addEventListener("input", showNext);
countInput.addEventListener("input", showNext);
Each addEventListener() call passes showNext itself, without parentheses, so the browser calls it on every change to either box.
Add this code to the end of main.js and save. The boxes may still hold eggs and 3 from the last step, so clear both of them first.
With both boxes empty, type fresh basil in Item. The line under the button grows a letter at a time, ending at Next: fresh basil ().
Type 2 in How many?, and it says Next: fresh basil (2). Now type e. The line drops back to Next: fresh basil (), because the box reads 2e as "" at that moment.
Like the click handler, showNext() reads value when its event fires, so the line matches the boxes after every edit Sam makes. If your code ever sets a box’s value itself, such as clearing it with value = "", call showNext() right after so the line catches up.
One thing still doesn’t work. Type an item and a count, then press Enter in the How many? box, as Sam would. Nothing happens, because Enter in a box on its own doesn’t click the Add button. In Send the Form Without a Reload, you’ll wrap the boxes in a form so that Enter adds the item too, and you’ll see what the browser does with a form unless you stop it.