Magento – Magento 2 product list quantity increment buttons

qty-increment

I have implemented the quantity increment buttons from https://magenticians.com/quantity-increment-decrement-magento-2/ and is working fine on product page. So I decided to implement it to list.phtml and buttons are displayed correctly but when I update quantity from a product all other quantities are updated too. Anyone knows how to update quantity for the item from I clicked the increment button?

I'm using the same code as Magenticians.
Thank you!

Best Answer

Magento 2 product listing page add quantity increase and decrease buttons

Add below HTML code in form of add to cart section

<div class="field qty">
    <div class="control qty-change">
      <button class="decreaseqty">-</button>
        <input type="hidden"
               name="qty"
               id="qty"
               value="<?= /* @escapeNotVerified */ $block->getProductDefaultQty() * 1 ?>"
               title="<?= /* @escapeNotVerified */ __('Qty') ?>"
               class="input-text qty"
               data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
               />

        <span class="qty-label"> 1 ITEMS </span>
      <button class="increaseqty">+</button>
    </div>
</div>

Add below jQuery in listing page

<script type="text/javascript">
    require(["jquery"],function($){
    jQuery(".increaseqty").click(function(e){
        e.preventDefault();
        var qty = jQuery(this).closest("div.control").find("input");
        var newqty = parseInt(qty.val())+parseInt(1);
        qty.val(newqty);
        var val = qty.val();
        var label = jQuery.mage.__('ITEMS');
        var changeQty = parseInt(val) + label;
        qtyLabel = jQuery(this).closest("div.control").find("span");
        jQuery(qtyLabel).text(changeQty);
        return false;
    });

    jQuery(".decreaseqty").click(function(){
        var qty = jQuery(this).closest("div.control").find("input");
        var newqty = parseInt(qty.val())-parseInt(1);
        if(newqty < 1){
            return false;
        }
        qty.val(newqty);
        var val = qty.val();
        var label = jQuery.mage.__('ITEMS');
        var changeQty = parseInt(val) + label;
        qtyLabel = jQuery(this).closest("div.control").find("span");
        jQuery(qtyLabel).text(changeQty);
        return false;

    });
});
</script>
Related Topic