1

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!

3
  • Is issue on product listing page right?
    – Abdul
    Commented Jan 2, 2018 at 10:36
  • only for simple product or configurable Commented Jan 2, 2018 at 10:53
  • Yes, in product listing page. I've added the same code in list.phtml Right now for simple products. Thank you!
    – mlavela
    Commented Jan 2, 2018 at 11:15

2 Answers 2

1

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>
2
  • I spend few weeks to find this solutions.Al last find this one.Thanks @Baharuni Asif
    – Anees
    Commented Dec 11, 2020 at 12:45
  • 1
    in 2024, I spend few hours and again find this solution and it works.
    – Anees
    Commented May 6 at 9:50
0

add below code in addtocart.phtml

<button class="action tocart primary decrease  qty_<?= /* @escapeNotVerified */ $_item->getId() ?>" data-bind="click: decreaseQty"><span class="minus"></span></button>
    <div class="input-text qty">
        <input id="qty_<?= /* @escapeNotVerified */ $_item->getId() ?>"
               name="qty"
               readonly
               data-bind="value: qty()"
               type="number"
               value="<?= $defaultQty ?>"
               readonly
               size="4"
               style="width:50px"
               title="<?= $block->escapeHtml(__('Qty')) ?>"
               class="input-text"
               data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
        />

    </div>
    <button class="action tocart primary increase" data-bind="click: increaseQty"><span class="Plus"></span></button>

create js file like qty_incr_decr.js and add below code

define([
'ko',
'uiComponent',
'jquery',
'Magento_Customer/js/customer-data'

], function (ko, Component,$,customerData) { 'use strict'; return Component.extend({

    minicartSelector: '[data-block="minicart"]',
    addToCartButtonSelector: '.action.tocart',
    messagesSelector: '[data-placeholder="messages"]',
    updateCartUrl : BASE_URL+'NameSpace_Module/cart/addToCart',
    ajaxRequest: [],

    initialize: function () {
        //initialize parent Component
        this._super();
        this.qty = ko.observable(this.defaultQty.toFixed(this.decimalPoint));
        var self = this;
    },
    decreaseQty: function() {

        var product_id = this.productId;

        if($('#qty_'+product_id).val() == 0) {
            this.qty($('#qty_'+product_id).val());
        }

        var newQty = parseFloat(this.qty()) - this.qtyIncrement;

        if (newQty < 0)
        {
            newQty = 0;

            return;
        }

        this.abortAjaxRequest(product_id);

        if(newQty < parseFloat(this.minCartQty)) {
            newQty = 0;
        }

        var availableQty = window.atob(this.saleableQty);

        if(availableQty < newQty) {
            newQty = parseFloat(availableQty);
        }

        this.addRemoveDeleteClass(newQty);
        $('.selling-format-qty-'+product_id).text(newQty.toFixed(this.decimalPoint));


        this.qty(newQty.toFixed(this.decimalPoint));
        $.cookie('cart_qty['+product_id+']',newQty);

        this.submitForm();

    },
    increaseQty: function() {
        var product_id = this.productId;
        if($('#qty_'+product_id).val() == 0) {
            this.qty($('#qty_'+product_id).val());
        }

        var availableQty = window.atob(this.saleableQty);

        if(availableQty < parseFloat(this.qty()) + this.qtyIncrement) {
            return;
        }


        this.abortAjaxRequest(product_id);

        var newQty = parseFloat(this.qty()) + this.qtyIncrement;

        if(newQty < this.minCartQty) {
            newQty = this.minCartQty;
        }

        this.addRemoveDeleteClass(newQty);
        $('.selling-format-qty-'+product_id).text(newQty.toFixed(this.decimalPoint));


        this.qty(newQty.toFixed(this.decimalPoint));

        $.cookie('cart_qty['+product_id+']',newQty);

        var self = this;

        this.submitForm();
    },

    submitForm: function() {

        var tmpId = "tocart-form_"+this.productId;

        this.ajaxSubmit($('[data-role='+tmpId+']'));
    },

    /**
     * @param {jQuery} form
     */
    ajaxSubmit: function (form) {
        var  formData;

        //$(this.minicartSelector).trigger('contentLoading');

        var self = this;
        var product_id = this.productId;
        formData = new FormData(form[0]);

        this.ajaxRequest[product_id] = $.ajax({
            url: this.updateCartUrl,
            data: formData,
            type: 'post',
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,

            /** @inheritdoc */
            success: function (res) {

                if(form.find('.cart-item-id').val() == '') {
                    form.find('[name="item_id"]').val(res.item_id);
                }

                if(self.qty() ==0) {
                    form.find('.cart-item-id').val('')
                }


            },

            /** @inheritdoc */
            error: function (res) {

            },

            /** @inheritdoc */
            complete: function (res) {
                if (res.state() === 'resolved') {
                    var response = res.responseJSON;
                    if(typeof $('#cart-item-'+response.item_id+'-qty').val() != "undefined"
                        && eval($('#cart-item-'+response.item_id+'-qty').val()) != eval(self.qty()))
                    {
                        self.ajaxSubmit(form);
                    } else {
                        $.cookie('cart_qty['+product_id+']',null);
                    }
                }
            }
        });
    },

    disableAddToCartButton: function () {
        var tmpId = "tocart-form_"+this.productId;
        var form = $('[data-role='+tmpId+']');
        var addToCartButton = form.find('.action.tocart');
        addToCartButton.attr("disabled", true);
    },

    enableAddToCartButton: function () {
        var tmpId = "tocart-form_"+this.productId;
        var form = $('[data-role='+tmpId+']');
        var addToCartButton = form.find('.action.tocart');
        addToCartButton.attr("disabled", false);
    },

    abortAjaxRequest: function (product_id) {
        if(this.ajaxRequest[product_id] != null) {
            this.ajaxRequest[product_id].abort();
            this.ajaxRequest[product_id] = null;
        }
    },

    addRemoveDeleteClass: function (newQty) {
        $('.qty_'+this.productId).removeClass('delete-qty');
        if(newQty == this.qtyIncrement) {
            $('.qty_'+this.productId).addClass('delete-qty');
        }
    }

});

});

then create addtocart controller and add logic for add product to cart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.