Adding Items
Now for the most important part: adding items from the page. When you click the Add button, the script should:
- read the name and the price from the text fields,
- make a new object from them and add it to the end of the array with
push(), - 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
- 1
Add a click handler to
addButton(addEventListener("click", ...)). In it, store the name (nameInput.value) in a constantnameand the price as a number (Number(priceInput.value)) in a constantprice. Then add the object{ name: name, price: price }toitemswithpush()and callshowItems(). Try it: typeCheeseand4and click Add. The total goes up to14. - 2
At the end of the click handler, clear both fields (set their
valueto""), so that you can type the next item right away.