简体   繁体   中英

How to update Shopping Cart Total properly in Javascript?

I am looking for some Javascript that will:

  • Update Cart Total on products selected (drop-down menu) and quantities entered

(*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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM