Multiple Prods w/ Objects
by davestein
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_1">5.00</span></td>
<td class="price">$<span id="total_price_1">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>
</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 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 );
add.onclick = function() {
product.items = product.items + 1;
qty.innerHTML = product.items;
};
sub.onclick = function() {
if ( product.items == 0 ) {
return false;
}
product.items = product.items - 1;
qty.innerHTML = product.items;
};
};
for ( var i = 0; i < products.length; ++i ) {
initializeProduct( products[i] );
}