Search code examples
javascriptjquerye-commercewebflow

Add in sets of 12 products to cart


Hello I have an issue with my code I would like to make the same thing but with a multiple of 12 and not the number 12

ex 12 beers, 24 beers etc but not 13, 14 or 15 beers.

Sorry my english is very bad.

https://bcambre-eshop.webflow.io/test

Thank you

<script>
// Initialize texts
$(".beer-info").hide();
$(".beer-info-alt").hide();
$(".checkout-abs").hide();
// select the target node — here : .cart-list
var target = document.getElementById('target');
// input here your reference value
var targetQty = 12;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        //console.log('cart update'); 
        setTimeout(function(){    
        var currentQty = $('.w-commerce-commercecartopenlinkcount').text();
        var leftQty = targetQty - currentQty ;
        // update counter — console.log('cans missing' + ' ' + leftQty);
            if ( leftQty <= 0 ) {
                $(".beers-left").text(leftQty);
                $(".beer-info").hide();
                $(".beer-info-alt").show();
                $(".checkout-abs").show();
            }
            else {
                    $(".beer-info-alt").hide();
                $(".checkout-abs").hide();
                    $(".beer-info").show();
                $(".beers-left").text(leftQty);  
            }
        // update progression stackbar — console.log(progressBar);
        var progressBar = currentQty / targetQty * 100;
        $(".completed-bar").css('width', progressBar + '%');      
    }, 300);
    });
});
// configuration of the observer:
var config = {
    attributes: false,
    childList: true,
    characterData: false
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
</script>


Solution

  • var leftQty = targetQty - (currentQty % targetQuantity);
    

    the Modulus operator % will give you the remainder after division of currentQuantity by target quantity. You can then subtract that from targetQuantity to get how many more beers fit in a pack.

    1 % 12 = 1
        12 - 1 = 11 beers remaining in a 12 pack
    
    13 % 12 = 1
        12 - 1 = 11 beers remaining in a 24 pack
    
    25 % 12 = 1
        12 - 1 = 11 beers remaining in a 36 pack
    

    etc

    You could display the current amount of packs beside your progress indicator.

    var totalPacks = Math.ceil(currentQuantity/targetQuantity)
    
    You have {leftQty} beers of pack {totalPacks}