Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a simple problem, the add to cart function isn't working as it should. When i click the delete button, it add something to the cart. But when i click the add to cart button, it doesn't output anything.


JavaScript
const products = [];
const carts = [];
const inputs = {
    productId: 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");
document.getElementById('btnAddProduct').onclick = addProduct;

function renderProductsTable(e) {
    // delete all entries
    [...productsTable.children].slice(1).forEach(entry => productsTable.removeChild(entry));
        for (product of products) {
            let tr = document.createElement('tr');
            tr.innerHTML = `<td>${ product.id }</td>
                            <td>${ product.desc }</td>
                            <td>${ product.qty }</td>
                            <td>${ product.price }</td>
                            <td>
                                <button id="${ product.id }">Delete</button>
                                <button id="${ product.id }">Add to Cart</button>
                            </td>`;

            productsTable.appendChild(tr);
            document.getElementById(product.id).addEventListener("click", removeProduct);
            document.getElementById(product.id).addEventListener("click", addCart);

            
        }

}
function renderCartsTable(e) {
    // delete all entries
    [...cartsTable.children].slice(1).forEach(entry => cartsTable.removeChild(entry));
        for (cart of carts) {
            let tr = document.createElement('tr');
            tr.innerHTML = `<td>${ product.id }</td>
                            <td>${ product.desc }</td>
                            <td>${ product.qty }</td>
                            <td>${ product.price }</td>
                             <td>${ product.price * product.qty }</td>
                            <td>
                                <button id="${ product.id }">Delete</button>
                            </td>`;
            cartsTable.appendChild(tr);
        }
         console.log(carts);
}
function addProduct() {
    const product = {
        id: inputs.productId.value,
        desc: inputs.desc.value,
        qty: Number(inputs.qty.value),
        price: Number(inputs.price.value)
    };
    if (product.id === '') {
        alert('Please enter a product id');
    return;
    }
        let existing = products.find(item => 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 => p.id === product_id);
    products.splice(index, 1);
    renderProductsTable();
}
function addCart(product_id) {
    const product = products.find(p => p.id === product_id);
    const cartItem = carts.find(c => c.product === product);
    if(cartItem) {
        cartItem.qty ++;
    }
    else {
            carts.push(product);
        }
        renderCartsTable();        
}



HTML
<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" 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>
<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</th>
        <th>Action</th>
    </tr>
</table>
<br />
</body>
<script src="script.js"></script>


What I have tried:

I tried several steps on how to fix it but it seems it still doesn't work. Hope you can help. Thanks.
Posted
Updated 13-Jul-17 5:25am
v2
Comments
Andy Lanng 13-Jul-17 11:13am    
Hi :)

1 solution

Ok - the ids of your dynamic buttons are all the same. You can't do that. It causes loads of issues.

Try this script. It still has problems, but the id's are unique at least:

JavaScript
const products = [];
const carts = [];
const inputs = {
    productId: 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");
document.getElementById('btnAddProduct').onclick = addProduct;

function renderProductsTable(e) {
    // delete all entries
    [...productsTable.children].slice(1).forEach(entry => productsTable.removeChild(entry));
        for (product of products) {
            let tr = document.createElement('tr');
            tr.innerHTML = `<td>${ product.id }</td>
                            <td>${ product.desc }</td>
                            <td>${ product.qty }</td>
                            <td>${ product.price }</td>
                            <td>
                                <button id="${ "del_" + product.id }">Delete</button>
                                <button id="${ "add_" + product.id }">Add to Cart</button>
                            </td>`;
							
            productsTable.appendChild(tr);
            document.getElementById("del_" + product.id).addEventListener("click", removeProduct);
            document.getElementById("add_" + product.id).addEventListener("click", addCart);
			
        }
		
}
function renderCartsTable(e) {
    // delete all entries
    [...cartsTable.children].slice(1).forEach(entry => cartsTable.removeChild(entry));
        for (cart of carts) {
            let tr = document.createElement('tr');
            tr.innerHTML = `<td>${ product.id }</td>
                            <td>${ product.desc }</td>
                            <td>${ product.qty }</td>
                            <td>${ product.price }</td>
                             <td>${ product.price * product.qty }</td>
                            <td>
                                <button id="${ "c_del_" + product.id }">Delete</button>
                            </td>`;
            cartsTable.appendChild(tr);
        }
         console.log(carts);
}
function addProduct() {
    const product = {
        id: inputs.productId.value,
        desc: inputs.desc.value,
        qty: Number(inputs.qty.value),
        price: Number(inputs.price.value)
    };
    if (product.id === '') {
        alert('Please enter a product id');
    return;
    }
        let existing = products.find(item => 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 => p.id === product_id);
    products.splice(index, 1);
    renderProductsTable();
}
function addCart(product_id) {
    const product = products.find(p => p.id === product_id);
    const cartItem = carts.find(c => c.product === product);
    if(cartItem) {
        cartItem.qty ++;
    }
    else {
            carts.push(product);
        }
        renderCartsTable();        
}
 
Share this answer
 
Comments
James Min 13-Jul-17 11:46am    
There is still a problem. I can't add a second product on the cart
Andy Lanng 14-Jul-17 4:07am    
Do you know how to debug the script?

There are several errors that you need to be able to find. In Chrome and IE you can press F12 to get the debug window up. You can see errors in the script and even step through it with break points to check the values.

For Firefox you need an extension called FireBug, but it works pretty much the same as the other two
James Min 13-Jul-17 12:53pm    
@Andy Lanng

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