Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys, I have a problem. The add to cart function doesn't work correctly. After i clicked the add to cart button, if it is the same Product ID, it does output a new product on another row. Another problem, is the total amount in the cart table.

What I have tried:

I tried using the find function but it still doesn't work. It still output a new product on another row. Please help me fix this. Thank you. BTW, here's my code below.

JavaScript
<!DOCTYPE html>
<html>
<head>
  <title>Shopping Cart ES6</title>
</head>
<body>
  <form name="order" id="order">
    <table>
      <tr>
        <td>
          <label for="productID">Product ID:</label>
        </td>
        <td>
          <input id="productID" name="product" type="text" size="28" required/>
        </td>
      </tr>
      <tr>
          <td>
              <label for="product">Product Desc:</label>
          </td>
          <td>
              <input id="product_desc" name="product" type="text" size="28" required/>
          </td>
      </tr>
      <tr>
          <td>
              <label for="quantity">Quantity:</label>
          </td>
          <td>
              <input id="quantity" name="quantity" width="196px" required/>
          </td>
      </tr>
      <tr>
          <td>
              <label for="price">Price:</label>
          </td>
          <td>
              <input id="price" name="price" size="28" required/>
          </td>
      </tr>
  </table>
  <input type="reset" class="resetbtn" value="Reset" />
  <input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<table border="1|1" id="products-table">
  <tr>
    <th>Product ID</th>
    <th>Product Description</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Action</th>
  </tr>
</table>
<br />
<h2>Shopping Cart</h2>
<table border="1|1" id="carts-table">
  <tr>
    <th>Product ID</th>
    <th>Product Description</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>Total Amount</th>
    <th>Action</th>
  </tr>
</table>
</body>
<script src="script.js">
</script>
</html>
 
<script>
//JS File

const products = [];
const carts = [];
const inputs = {
  id: document.getElementById("productID"),
  desc: document.getElementById("product_desc"),
  qty: document.getElementById("quantity"),
  price: document.getElementById("price")
};
const productsTable = document.getElementById("products-table");
const cartsTable = document.getElementById("carts-table");

function renderProductsTable() {
  // delete all entries
  Array.from(productsTable.children).slice(1).forEach(entry =&gt; productsTable.removeChild(entry));
    
    for (product of products) {
      const tr = document.createElement('tr');
      const id = document.createElement('td');
      id.textContent = product.id;
      const desc = document.createElement('td');
      desc.textContent = product.desc;
      const qty = document.createElement('td');
      qty.textContent = product.qty;
      const price = document.createElement('td');
      price.textContent = product.price;
      const action = document.createElement('td');
      const deleteButton = document.createElement('button');
      deleteButton.textContent = 'Delete';
      deleteButton.addEventListener('click', () =&gt; removeProduct(product.id))
      const addToCartButton = document.createElement('button');
      addToCartButton.textContent = 'Add to cart';
      addToCartButton.addEventListener('click', () =&gt; addCart(product.id));
      action.appendChild(deleteButton);
      action.appendChild(addToCartButton);
      tr.appendChild(id);
      tr.appendChild(desc);
      tr.appendChild(qty);
      tr.appendChild(price);
      tr.appendChild(action);
      productsTable.appendChild(tr);
      console.log(products); 
    }

}

function addProduct() {
  
  const product = {
  id: inputs.id.value,
  desc: inputs.desc.value, 
  qty: Number(inputs.qty.value),
  price: Number(inputs.price.value)
  };

  let existing = products.find(item =&gt; item.id === product.id);

  if (existing) {
  existing.qty += product.qty;
  } 
  else {
   products.push(product);
  }
  renderProductsTable();
  document.getElementById('order').reset();
  }



function removeProduct(product_id) {
  const index = products.findIndex(p =&gt; p.id === product_id);
  products.splice(index, 1);
  renderProductsTable();
}

function addCart(product_id) {
      const product = products.find(p =&gt; p.id === product_id);
      const cartItem = carts.find(c =&gt; c.product === product);
      if(cartItem) {
        cartItem.qty += 1;
      }
      else {
        carts.push(product);
      }
      renderCartTable();
            console.log(cartItem);
}

function renderCartTable() {
  for (cart of carts){
    const tr = document.createElement('tr');
    const id = document.createElement('td');
    id.textContent = cart.id;
    const desc = document.createElement('td');
    desc.textContent = cart.desc;
    const qty = document.createElement('td');
    qty.textContent = cart.qty;
    const price = document.createElement('td');
    price.textContent = cart.price;
    const total = document.createElement('td');
    total.textContent = "Total Amount Should Calculate Here Automatically"
    const action = document.createElement('td');
    const subtractButton = document.createElement('button');
    subtractButton.textContent = 'Subtract Quantity';
    const addButton = document.createElement('button');
    addButton.textContent = 'Add Quantity';
    const removeButton = document.createElement('button');
    removeButton.textContent = 'Remove Item';
    tr.appendChild(id);
    tr.appendChild(desc);
    tr.appendChild(qty);
    tr.appendChild(price);
    tr.appendChild(total);
    tr.appendChild(action);
    cartsTable.appendChild(tr);
    console.log(carts);
  }
}
</script>
Posted
Updated 11-Jul-17 22:41pm
v2

1 solution

Here it is in jsfiddle:
Add cart not working - JSFiddle[^]

But it works as expected.

I made a couple of changes just to get it to run, such as populating the elements on doc.ready, just to get it to fit with jsfiddle.

I also made the functions arrow functions.

I guess I don't get when you load the script? Maybe by the time it runs the document hasn't finished loading all the elements?

Try looking at jQuery. It works great with ES6. Instead of looking for the element you can set selectors, which act as pointers to elements that match. It's a much more consistent way of getting hold of your elements. Here, look:

JavaScript
let id = document.getElementById("productID")
//id will be null if the element hasn't loaded yet
id = $("productID")
//this will be evaluated when it's called.  It will return an array btw
 
Share this answer
 
Comments
James Min 13-Jul-17 2:19am    
@Andy Lanng. We were instructed using plain javascript only. It still doesn't work. When we add the same product with the same ID, it still output a new row.
Andy Lanng 13-Jul-17 4:24am    
What browser are you using? JsFiddle works fine in Chrome and Firefox. Not at all in IE. That might give us a clue.
Andy Lanng 13-Jul-17 4:31am    
Also, why is your script link in such an odd place? have you tried moving it to a document.addEventListener("DOMContentLoaded",function(){...});? it may solve all your issues
James Min 13-Jul-17 10:17am    
Yes its adding to cart. But the thing is, once it has the same product ID, it must increase its quantity and not add a new product in the cart table
Andy Lanng 13-Jul-17 10:26am    
Look at my jsFiddle. I took your code and I cannot make it create two rows with the same ID. There must be something else going on outside of what you have shown me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900