Calculator: Grocery Cart
Simple grocery cart calculator
by Joey Albert Abano
HTML
<div>
<div class="tindahan-product-list">
</div>
<div id="product-item-new-tpl" class="product-item-new">
<input type="text" name="name" placeholder="Product">
<input type="text" name="price" placeholder="0.00">
<input type="text" name="quantity" value="1">
<button class="product-add" class="">+</button>
</div>
</div>
<div id="product-item-modify-tpl" class="hide">
<div class="product-item-modify">
<input type="text" name="name" placeholder="Product">
<input type="text" name="price" placeholder="0.00">
<input type="text" name="quantity" placeholder="Quantity">
<button class="product-remove">x</button>
</div>
</div>
<div class="tindahan-fixed-bottom">
<span>Total:</span> <span id="tindahan-product-total"></span>
</div>
CSS
input[name="price"] {
text-align: center;
width: 44px;
}
.hide {
display: none;
}
input[name="quantity"] {
text-align: center;
width: 22px;
}
.hide {
display: none;
}
body {
background:#222;
color:#fff;
font-family: consolas
}
body, input {
font-size:14px;
}
input {
background:none;
color:#fff;
width:120px;
}
h1 {
font-size:18px;
}
h2 {
font-size:16px;
}
JavaScript
var productobj = {};
$(function() {
$('input').on('keyup', function() {
var uid = $(this).data('uid');
var product = productobj[uid];
product[$(this).attr('name')]=$(this).val();
product = validate(product);
productobj[uid] = product;
computesum();
});
$('button.product-add').on('click', function() {
var source = $('#product-item-new-tpl');
var item = $('#product-item-modify-tpl div.product-item-modify').clone(true);
var uid = Date.now() + Math.random();
var product = {};
source.find('input[type="text"]').each(function() {
var el = $(this);
var inputtext = item.find('input[name="' + el.attr('name') + '"]');
inputtext.val(el.val());
inputtext.data('uid', uid);
product[el.attr('name')] = el.val();
if (el.attr('name') == 'quantity') {
el.val(1);
} else {
el.val('');
}
});
item.find('button.product-remove').data('uid', uid);
product = validate(product);
if (!product.status) {
// highlight the product row
}
productobj[uid] = product;
$('div.tindahan-product-list').append(item);
console.debug('product list', productobj);
computesum();
});
$('button.product-remove').on('click', function() {
delete productobj[$(this).data('uid')];
$(this).parent().remove();
});
});
function validate(product) {
product.status = true;
product.quantity = parseInt(product.quantity);
product.price = parseFloat(product.price);
if (Number.isNaN(product.quantity)) {
product.quantity = 1;
product.status = false;
}
if (Number.isNaN(product.price)) {
product.price = 0.00;
product.status = false;
}
return product;
}
function computesum() {
var totalsum = 0;
$.each(productobj, function(index, product) {
var itemsum = product.price * product.quantity;
totalsum = totalsum+itemsum;
});
$('#tindahan-product-total').html(totalsum.toFixed(2));
}