Albert
Albert

Reputation: 23

Remove, Save and Qty Update in Shopping Cart with JavaScript

New to learning to code. I have a simple Book Shopping Cart page here:

Shopping cart

The goal here is to ADD to cart, SAVE cart contents and REMOVE items from cart all at will using the template from Instructor. We went over the Onload and Building the cart sections, learned how to Add to cart, and then we were to discover how to Save, Remove and Update Qty and Total of the Cart.

I have written some code that allows me to click the Remove button on screen so the Book Count and Total reflect the items are being removed but the items still remain on screen in the cart. I have tried to look for answers to the SAVE and QTY update parts but no dice. I can not figure this out. Any and all advice would be greatly appreciated. Thank you.

    // Shopping Cart Assignment

    // You can use this data for seeding your cart
    // Or you can create your own

    books = [
      {
        title: "Absolute Java",
        qty: 1,
        price: 114.95,
      },
      {
        title: "Pro HTML5",
        qty: 1,
        price: 27.95,
      },
      {
        title: "Head First HTML5",
        qty: 1,
        price: 27.89,
      },
    ];

    onload = () => {
      //check for localStorage
      var myCart = localStorage.getItem("myCart");
      //if exist then
      if (myCart) {
        //load from localStorage
        books = JSON.parse(myCart);
      } else {
        //else load default data ( books )
      }
      buildCart();
      updateCount();
      updateTotal();

      let btnAdd = document.querySelector("#add");
      btnAdd.addEventListener("click", addItem);

      let btnRemove = document.querySelector("#remove");
      btnRemove.addEventListener("click", removeItem);

      let btnSave = document.querySelector("#save");
      btnSave.addEventListener("click", saveCart);
    };

    const buildCart = () => {
      var tbody = document.querySelector("tbody");
      for (let book of books) {
        let str = `
            <tr>
                <td>
                    <input class="title" value="${book.title}"/>
                </td>
                <td>
                    <input class="qty" size="2" value="${book.qty}"/>
                </td>
                <td>
                    <input size="2" value="${book.price}"/>
                </td>
                <td>${book.price}</td>
                <td>${updateLineTotal(book)}</td>
                <td>
                <button id="remove" onclick="removeItem()">
                    Remove
                </button>
                </td>
            </tr>
        `;
        tbody.innerHTML += str;
      }
    };

    const addItem = () => {
      let book = {
        title: "Crazy Cool CSS",
        qty: 1,
        price: 34.95,
      };

      let str = `
        <tr>
            <td>
                <input class="title" value="${book.title}"/>
            </td>
            <td>
                <input class="qty" size="2" value="${book.qty}"/>
            </td>
            <td>
                <input size="2" value="${book.price}"/>
            </td>
            <td>${book.price}</td>
            <td>${updateLineTotal(book)}</td>
            <td>
            <button id="remove" onclick="removeItem()">
                Remove
            </button>
            </td>
        </tr>
        `;
      var tbody = document.querySelector("tbody");
      tbody.innerHTML += str;

      books.push(book);
      updateCount();
      updateTotal();
    };

    const saveCart = () => {};

    const updateCount = () => {
      document.querySelector("#count").innerHTML = books.length;
    };

    const updateTotal = () => {
      var total = 0;
      for (let book of books) {
        total += book.price * book.qty;
      }
      document.querySelector("#total").innerHTML = total.toFixed(2);
    };

    const updateLineTotal = (book) => {
      return (book.price * book.qty).toFixed(2);
    };

    const removeItem = (book) => {
      let myCart = localStorage.getItem("myCart");
      myCart = JSON.parse(myCart);

      for (var i in myCart) {
        if (myCart != null) {
          localStorage.removeItem("#bookA");
          localStorage.removeItem("#bookB");
          localStorage.removeItem("#bookC");
          localStorage.removeItem("#bookD");
        } else {
          alert("Book Removed");
        }
      }

      books.pop(book);
      updateCount();
      updateTotal();
    };
    <!DOCTYPE html>
    <html>
      <head>
        <title>Book Shopping Cart</title>
        <meta charset="UTF-8" />
        <script src="cart.js"></script>
        <link rel="stylesheet" href="cart.css" />
      </head>

      <body>
        <table>
          <caption>
            <b>My Books</b>
          </caption>
          <thead>
            <tr>
              <th>Title</th>
              <th>Qty</th>
              <th>UnitPrice</th>
              <th>$UnitPrice</th>
              <th>Line Total</th>
              <th>Total $<span id="total"></span></th>
            </tr>
          </thead>
          <tbody></tbody>
          <tfoot>
            <tr>
              <td colspan="3">
                <button id="add">New</button>
              </td>
              <td colspan="3">
                <button id="save">Save</button>
              </td>
            </tr>
          </tfoot>
        </table>
        <b>Book Count : <span id="count">0</span></b>
      </body>
    </html>

I appreciate your time. Thank you.

Upvotes: 2

Views: 394

Answers (1)

iamdlm
iamdlm

Reputation: 1983

First you need to replace the id attribute from button, because ids cannot be repeated in DOM.

<button id="remove" onclick="removeItem()">Remove</button>

let btnRemove = document.querySelector("#remove");

With:

<button class="remove" onclick="removeItem()">Remove</button>

let btnRemove = document.querySelector(".remove");

One way of doing what you want is to add a property id for each book, (which should be unique).

books = [{
     id: 1,
     title: "Absolute Java",
     qty: 1,
     price: 114.95,
   },
   {
     id: 2,
     title: "Pro HTML5",
     qty: 1,
     price: 27.95,
   },
   {
     id: 3,
     title: "Head First HTML5",
     qty: 1,
     price: 27.89,
   },
];

When you're building your HTML make each row id equal to the book id

<tr id="${book.id}">

And use that id as a parameter for the remove method:

<button class="remove" onclick="removeItem(${book.id})">
    Remove
</button>

Finally your remove method should receive the book id parameter and remove the row element from DOM and filter books removing the book with the same id.

const removeItem = (id) => {
   var row = document.getElementById(id);
   row.remove();

   // same as remove    
   books = books.filter(bk => {
     return bk.id !== id;
   });

   updateCount();
   updateTotal();
 };

Side note: when adding a new book you can generate a unique id with:

let book = {
    id: Math.random().toString(16).slice(2),
    title: "Crazy Cool CSS",
    qty: 1,
    price: 34.95,
};

JSFiddle

Upvotes: 1

Related Questions