Reputation: 43
I'm building a mock e-commerce store where I try to get the functionality working properly. Currently, I have a shop page where, if I click 'add to cart' a function is invoked which adds the corresponding product to an array (the 'cart') called cartItems.
The problem is trying to display the data that is held within that array on the cart page. I would like to build a table that can both hold multiple products and also be stylised. I'm not entirely sure how to achieve this.
I've read through and tried using stringify with little success. I think that this is the best option but am not sure.
This is code which adds the product to the cart
let cartItems = [];
const addToCartBtns = [...document.querySelectorAll(".atc-button")];
addToCartBtns.forEach(button => {
button.addEventListener("click", function(){
const productSKU = button.getAttribute('data-product-id'),
product = catalog.findById(productSKU);
cartItems.push({
sku: productSKU,
qty: 1,
productInfo: product
});
This is the information which is pushed to the array.
class Product {
constructor(propsObj) {
this.id = propsObj.id;
this.title = propsObj.title;
this.description = propsObj.description;
this.imgUrl = propsObj.imgUrl;
this.price = propsObj.price;
this.readMore = propsObj.readMore;
}
This is what the array data looks like once added
0:
productInfo: Product
description: "Sed portitor lectus nibh. Curabitur aliquet quam id
dui posuere blandit. Lorem ipsumo dolor sit amet, consictetur
adipiscing elit."
id: "00001"
imgUrl: "https://source.unsplash.com/9489sFfgk4c/1000x1000"
price: 1999
readMore: "st-helen-chair.html"
title: "St. Helen Chair"
__proto__: Object
qty: 1
sku: "00001"
A table on the cart page which includes any products currently sitting in the cartItems array. Ideally, also a way to remove the product from the array/cart and also to change the quantity.
Upvotes: 1
Views: 361
Reputation: 129
This would be an example of how to display data dynamically in a table using es6 template strings.
content.innerHTML = `<table id='productTable'>
<tr>
<th>name</th>
<th>description</th>
<th>price</th>
<th>quantity</th>
<th>remove</th>
</tr>`
+
(cartItems.map(createProductTableRow).join('\n'))
+
`</table> `;
function createProductTableRow(product) {
return `
<tr>
<td>${product.productInfo.title}</td>
<td>${product.productInfo.description}</td>
<td>${product.productInfo.price}</td>
<td>${product.qty}</td>
<td><button class='remove'>Remove Item</button></td>
</tr>`;
}
You can style the table using it's id "productTable" via css. The last entry of every row also contains a dynamically created button of class "remove" for which you can write your javascript code to remove items. Again just an example, you can create arbitrary html markup dynamically with this method .
Upvotes: 1