Greetings Independently decided to develop a basket script on jquery.

I managed to sum up the quantity of goods and their total prices, but I can’t understand how to subtract the total amount by pressing a certain button - that is, subtract the cost of the last added product from the total amount.

Below is the code:

$(document).ready(function(){ //add price and quantity in shoping cart $(".item_shop").on("click",".in_cart", function() { var price = +$(this).closest(".item_shop").data("price"); $("#summ").text(function(i, val) { return val * 1 + price; }); $("#items").text(function(i, val) { return val * 1 + 1; }); }); //remove items and quantity in shopnig cart $(".right").on("click", function(event) { event.preventDefault(); var price = +$(this).closest(".item_shop").data("price"); $("#summ").prev().val($("#summ").text()); // в данной строке все никак не могу придумать, что прописать чтобы уменьшалась сумма последнего добавленного товара. $("#items").text(function(i, val) { return val * 1 - 1; // здесь количество минусует, но также уходит в минус, что конечно не желательно. }); }); });// end of function 

Thank you in advance.

    1 answer 1

    The principle of the basket implementation is not correct. It is necessary somewhere to save all the goods in the basket (well, if not the goods, as in this case, then at least prices)

     $(document).ready(function(){ window.basket = { prices: [], // массив всех цен на все товары sumPrice: 0 // общая цена, если вдруг она изначально не 0 - задать ее }; $(".item_shop").on("click",".in_cart", function() { var price = +$(this).closest(".item_shop").data("price"); basket.prices.push(price); basket.sumPrice += price; update(); }); $(".right").on("click", function(event) { event.preventDefault(); var lastPrice = basket.prices.pop(); if(!lastPrice) return; // защита, чтобы меньше 0 не было:D basket.sumPrice -= lastPrice; update(); }); function update() { $("#summ").text(basket.sumPrice); $("#items").text(basket.prices.length); } });// end of function 

    • Many thanks for the detailed answer! However, the button with the class right for some reason still does not work (does not decrease) - ilnur
    • shop.js: 21 Uncaught ReferenceError: price is not defined (anonymous function) @ shop.js: 21dispatch @ jquery.min.js: 3r.handle @ jquery.min.js: 3 - ilnur
    • @ilnur discard, please, more code so that you can see what's wrong. can be on plnkr.co/edit/?p=catalogue or jsfiddle.net (or wherever) - sanix
    • plnkr.co/edit/w1kc6W5KMEwj5Kq4Z3dG?p=preview link to the part of the stmm code containing the cart and button. ex-citer.myjino.ru/9/index.html link to the page completely - .right is the arrow to the right under the slider. I am forming on the bootstrap. - ilnur
    • @ilnur error was basket.sumPrice -= lastPrice; where instead of lastPrice was price . + added protection to less than 0 was not - sanix