Checking the Input
Try clicking Add with both fields empty. An item with no name for €0 appears in the list. A good app doesn't accept data like that: it checks what the user has typed, and if something is wrong, it says what.
The checks go at the start of the click handler, before the item is added. If something is wrong, the handler shows a message in the message paragraph and ends with return. As you know from the lesson on functions, return ends the function, so the code that adds the item doesn't run:
if (name === "") {
message.textContent = "Enter what you want to buy.";
return;
}What about the price? When the price field is empty, its value is the empty text "", and Number("") is 0. A field for numbers also gives you empty text when what's in it isn't a valid number. So a single condition, price <= 0, catches an empty price as well as zero and negative prices.
And when everything is fine, an old message must not stay on the page, so clear it before you add the item.
Instructions
- 1
At the start of the click handler (right after reading
nameandprice), add a condition: ifnameis empty (""), showEnter what you want to buy.inmessageand end the handler withreturn. - 2
Add a second condition: if
priceis0or less, showEnter a price greater than 0.inmessageand end the handler withreturn. - 3
When both checks pass, clear the message (
message.textContent = "") before adding the item. Try it: click Add with an empty field, and then add a proper item. The message disappears.