1

Trying to limit the total quantity of items allowed to be added to 4, this function alerts first time but still adds items to the cart.

simpleCart.bind( 'beforeAdd' , function( item ){

        if(simpleCart.quantity() === 4 ){

             alert("You can only compare 4 items."); 
             return false;

        }

   });
user1199795
  • 63
  • 1
  • 11

2 Answers2

0

It only checks for the 4th element added and keeps adding elements. If you make it to check if the quantity is equal or bigger than 4 to prevent adding more items :)

simpleCart.bind( 'beforeAdd' , function( item ){

    if(simpleCart.quantity() >= 4 ){

         alert("You can only compare 4 items."); 
         return false;

    }

});
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
0

SimpleCart (v3) passes an item to beforeAdd that represents only the item and quantity that is being added to the cart. The code needs to take into account any items already in the cart.

simpleCart.bind('beforeAdd', function (item) {
    var requestedQuantity = item.get('quantity');
    var existingItem = simpleCart.has(item);
    if (existingItem) {
        requestedQuantity += existingItem.get('quantity');
    }
    if (requestedQuantity > 4) {
        alert("You may compare at most 4 items.");
        return false;
    }
});
Matthew K
  • 973
  • 6
  • 21