I've got a JavaScript object and I am not sure how to implement the last part: adding up all of the prices and putting that in the last row of the table. Besides this question, I would also like to ask you to look at the code and advice me if I can make the code slimmer, less lines of code.
This is the code I would like reviewed:
function ShoppingList(){
this.items = [];
this.setItem = function(product, price){
var item = new Item(product, price);
this.items.push(item);
};
this.render = function(){
var placeHolder = document.getElementById("shoppingList");
placeHolder.innerHTML = "";
var messageDiv = document.getElementById("message");
messageDiv.innerHTML = "";
var tr = document.createElement("tr");
tr.id = "header";
var thProduct = document.createElement("th");
thProduct.innerHTML = "Product";
tr.appendChild(thProduct);
var thPrice = document.createElement("th");
thPrice.innerHTML = "Prijs";
tr.appendChild(thPrice);
var thDel = document.createElement("th");
thDel.innerHTML = "Verwijder";
tr.appendChild(thDel);
placeHolder.appendChild(tr);
for(var i = 0; i < this.items.length; i++){
var tr = document.createElement("tr");
tr.id = i;
var tdProduct = document.createElement("td");
tdProduct.innerHTML = this.items[i].product;
tr.appendChild(tdProduct);
var tdPrice = document.createElement("td");
tdPrice.innerHTML = Number(this.items[i].price);
tr.appendChild(tdPrice);
var tdDel = document.createElement("td");
tdDel.innerHTML = "Verwijder";
tdDel.addEventListener("click", delItem, false);
tr.appendChild(tdDel);
placeHolder.appendChild(tr);
}
};
}
So, in short: how can I write a new table row to the table with the total price that updates when table rows are added or removed and how can I slim down my code?