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
At the start of the click handler (right after reading name and price), add a condition: if name is empty (""), show Enter what you want to buy. in message and end the handler with return.
Add a second condition: if price is 0 or less, show Enter a price greater than 0. in message and end the handler with return.
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.
Start programming for free
4/6