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:
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) {
[...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) {
[...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();
}