I have created a table that creates new rows automatically after an onclick
event. Also the code create a button that delete the rows when it's clicked.
The problem that I can't solve it's when I click for the second time the 'add row onclick event' I get two copies of the same row.
Thank you in advance for anyone can help me, here below you can find the code:
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("orderedProductsTbl").deleteRow(i);
}
//this function manipulates DOM and displays content of our shopping cart
var shoppingCart = [];
function displayShoppingCart(){
var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
//ensure we delete all previously added rows from ordered products table
while(orderedProductsTblBody.rows.length>0) {
orderedProductsTblBody.deleteRow(0);
}
//variable to hold total price of shopping cart
var cart_total_price=0;
//iterate over array of objects
for(var product in shoppingCart){
//add new row
var row=orderedProductsTblBody.insertRow();
//add button
var removeRow=document.createElement("Button");
//set up button
removeRow.innerHTML= "Delete";
removeRow.setAttribute("onClick", "deleteRow(this)");
//create four cells for product properties
var cellName = row.insertCell(0);
var cellDescription = row.insertCell(1);
var cellPrice = row.insertCell(2);
var cellDelete = row.insertCell(3);
cellPrice.align="center";
cellDescription.align ="right";
cellDelete.align="right";
cellName.height="40"
cellPrice.height="40";
cellDescription.height="40";
cellDelete.height="40"
//fill cells with values from current product object of our array
cellName.innerHTML = shoppingCart[product].Name;
cellDescription.innerHTML = shoppingCart[product].Description;
cellPrice.innerHTML = shoppingCart[product].Price;
cellDelete.appendChild( removeRow );
cart_total_price+=shoppingCart[product].Price;
}
//fill total cost of our shopping cart
document.getElementById("cart_total").innerHTML=cart_total_price;
}
function AddtoCart(name,description,price){
//Below we create JavaScript Object that will hold three properties you have mentioned: Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name=name;
singleProduct.Description=description;
singleProduct.Price=price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
displayShoppingCart();
}