Reputation: 133
I am looking for some Javascript that will:
(*Security will be handled by back-end PHP. I have attempted this over the last three days but apparently my code was so bad I feel ashamed to repost it here again)
My Thinking:
- Create a cart object
- Make a function that recalculates the total on any changes that occur
(I can not think of anything else this would require given the javascript will just be passing this over to a PHP script to check anyway)
Does anyone know of some javascript that does the job I seek? Is my thinking correct?
Upvotes: 0
Views: 11155
Reputation: 4809
Below is sample shopping cart javascript object built using revealing module pattern.
var shoppingCart = function () {
var obj = {}, items = [];
obj.AddItem = function (itemNo, quantity, price) {
var item = {};
item.itemNo = itemNo;
item.quantity = quantity;
item.price = price;
items.push(item)
};
obj.GetAllItems = function () {
return items;
};
obj.GetItemByNo = function (item) {
for (var i = 0; i < items.length; i++) {
if (items[i].itemNo === item)
return item[i];
}
return null;
};
obj.CalculateTotal = function () {
var total = 0;
for (var i = 0; i < items.length; i++) {
total = total + (items[i].quantity * items[i].price);
}
return total;
};
return obj;
};
var cart = new shoppingCart();
Add items using AddItem method, include additional properties that are useful in the UI.
shoppingcart.AddItem(2,4,2.4);
Gets list of items in the shopping cart
var items = shoppingcart.GetAllItems();
Calculates total price of items in shopping cart
var total = shoppingcart.CalculateTotal();
Please note that I have typed this code in here, so might contain typo's and also I recommend having data type validations for price and quantity as numerics before adding item.
Upvotes: 3