Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

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

Back

3/9

  1. 1. Shopping List
  2. 2. The Total
  3. 3. Adding Items
  4. 4. Checking the Input
  5. 5. Crossing Off Items
  6. 6. Items from a File
  7. 7. Saving the List
  8. 8. Removing Bought Items
  9. 9. Congratulations!
Next

Try it yourself

Do this exercise right here in your browser. No account needed.