Adding Items

Now for the most important part: adding items from the page. When you click the Add button, the script should:

  1. read the name and the price from the text fields,
  2. make a new object from them and add it to the end of the array with push(),
  3. show the list again with showItems(), which also updates the total.

Read the fields inside the click handler, the function that runs when the button is clicked. It runs only at that moment, so it reads what's in the fields right then. If you read them at the top of the script, you'd get what was in them when the page loaded: empty text.

And remember that the value of a text field is always text, even in a field for numbers. Without Number(), the price would be the text "4", and the total would join texts instead of adding numbers: 10 + "4" gives "104".

Each time you click Run, the page loads anew, and the list starts over with the three items from the array.

Instructions

Add a click handler to addButton (addEventListener("click", ...)). In it, store the name (nameInput.value) in a constant name and the price as a number (Number(priceInput.value)) in a constant price. Then add the object { name: name, price: price } to items with push() and call showItems(). Try it: type Cheese and 4 and click Add. The total goes up to 14.

At the end of the click handler, clear both fields (set their value to ""), so that you can type the next item right away.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/6