Update Cart Grand Total
grand total function showing for object loop
HTML
<form id="say-form" onsubmit="return false;" action="#">
<table cellspacing="0" cellpadding="0">
<tr>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th colspan="2">Total</th>
</tr>
<tr>
<td class="title">Prod A</td>
<td class="qty" id="qty_a">0</td>
<td class="price">$<span id="price_a">5.00</span></td>
<td class="price">$<span id="total_price_a">0.00</span></td>
<td>
<input type="button" id="add_a" value="+" />
<input type="button" id="sub_a" value="-" />
</td>
</tr>
<tr>
<td class="title">Prod B</td>
<td class="qty" id="qty_b">0</td>
<td class="price">$<span id="price_b">10.00</span></td>
<td class="price">$<span id="total_price_b">0.00</span></td>
<td>
<input type="button" id="add_b" value="+" />
<input type="button" id="sub_b" value="-" />
</td>
</tr>
<tr>
<td></td>
<td colspan="2" style="font-weight: bold;">Grand Total:</td>
<td>$<span id="grand_total">0.00</span></td>
</tr>
</table>
</form><br />
<br />
<div id="cart"></div>
CSS
td, th { padding: 3px 0; }
th { font-weight: bold; }
.title { width: 100px; }
.qty { width: 50px; }
.price { width: 75px; }
tr:hover td { background-color: #EFEFEF; }
input { padding: 3px; }
JavaScript
var products = [ 'a', 'b' ];
var prod_info = {
a : {
items : 0,
price : 5,
color : 'red'
},
b : {
items : 0,
price : 10,
color : 'blue'
}
};
var updateGrandTotal = function() {
var grand_total = 0;
for ( key in prod_info ) {
// prod_info[ key ] equals { items : x, price : y }
// grand_total = grand_total + ( ??? );
}
document.getElementById( 'grand_total' ).innerHTML = grand_total.toFixed( 2 );
};
// This function takes 3 arguments
var updateItems = function( product, qty, total_price ) {
var price = product.items * product.price;
qty.innerHTML = product.items;
total_price.innerHTML = price.toFixed( 2 );
updateGrandTotal();
};
var initializeProduct = function( product_id ) {
var product = prod_info[ product_id ];
var qty = document.getElementById( 'qty_' + product_id );
var add = document.getElementById( 'add_' + product_id );
var sub = document.getElementById( 'sub_' + product_id );
var total_price = document.getElementById( 'total_price_' + product_id );
add.onclick = function() {
product.items = product.items + 1;
updateItems( product, qty, total_price );
};
sub.onclick = function() {
if ( product.items == 0 ) {
return false;
}
product.items = product.items - 1;
updateItems( product, qty, total_price );
};
};
for ( var i = 0; i < products.length; ++i ) {
initializeProduct( products[i] );
}