How To Add Quantity Increment And Decrement Button On Product page Magento 2

E-commerce store owners are constantly working to improve the online shopping experience and make it more convenient for customers. One way to achieve this is by adding useful features to the product page. These features can include size charts, easy returns, quantity change buttons, WhatsApp sharing buttons, order tracking, and more.

In this case, we are discussing the implementation of quantity increment and decrement buttons in Magento 2. By adding these buttons, customers can easily increase or decrease the quantity of products in their shopping cart directly on the product page.

The code for implementing these buttons is written using Knockout JS, a lightweight JavaScript library. Knockout JS is used to enhance the functionality of the product page without adding unnecessary complexity.

Method To Add Increment And Decrement Button On Product page. 
Follow these steps:
1-For adding Increment And Decrement Button on the product page you need a create custom module.
Like:
Vendor/Module
Esparksinc/QtyCounterProductPage
2-Copy addtocart.phtml from the default store of Magento.
Go on the path:
vendor/magento/module-catalog/view/frontend/templates/product/view
From the root directory of your store and copy addtocart.phtml to your module.
Path:
app/code/Esparksinc/QtyCounterProductPage/view/frontend/templates/product/view
Now edit addtocart.phtml file it will look like:

And paste this code into it:


<?php   
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/** @var $block \Magento\Catalog\Block\Product\View */
?>
<?php $_product = $block->getProduct(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
<?php if ($_product->isSaleable()): ?>
<div class="box-tocart">
   <div class="fieldset">
       <?php if ($block->shouldRenderQuantity()): ?>
       <div class="field qty">
       <label class="label" for="qty"><span><?php /* @escapeNotVerified */ echo __('Qty') ?></span></label>
<script type="text/x-magento-init">
{
   "*": {
       "Magento_Ui/js/core/app": {
           "components": {
               "change_qty": {
                   "component": "Esparksinc_QtyCounterProductPage/js/view/product/view/change_qty",
                   "defaultQty": <?php echo $block->getProductDefaultQty() * 1 ?>
               }
           }
       }
   }
}
</script>
<div class="control" data-bind="scope: 'change_qty'">
   <button data-bind="click: decreaseQty">-</button>
   <input  data-bind="value: qty()"
   type="number"
   name="qty"
   id="qty"
   maxlength="10"
   title="<?php echo __('Qty') ?>"
   class="input-text qty"
   data-validate="<?php echo $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
   />
   <button data-bind="click: increaseQty">+</button>
</div>
       </div>
       <?php endif; ?>
       <div class="actions">
       <button type="submit"
               title="<?php /* @escapeNotVerified */ echo $buttonTitle ?>"
               class="action primary tocart"
               id="product-addtocart-button">
           <span><?php /* @escapeNotVerified */ echo $buttonTitle ?></span>
       </button>
       <?php echo $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>
<?php endif; ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
       "Magento_Catalog/product/view/validation": {
           "radioCheckboxClosest": ".nested"
       }
       }
   }
</script>
<?php if (!$block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
       "catalogAddToCart": {
           "bindSubmit": false
       }
       }
   }
</script>
<?php endif; ?>
  • The block at the top (/** @var $block \Magento\Catalog\Block\Product\View */) defines the variable $block as an instance of the \Magento\Catalog\Block\Product\View class.
  • The $_product variable is assigned the value of the current product using the $block->getProduct() method.
  • The code checks if the product is saleable (‘if ($_product->isSaleable())’) and proceeds to display the add-to-cart section if it is.
  • The quantity input field is rendered using a combination of HTML and KnockoutJS data-bind attributes.
  • The code includes JavaScript snippets to initialize and configure the quantity change functionality.


3-Create a change_qty.js file on the path.
    app/code/Esparksinc/QtyCounterProductPage/view/frontend/web/js/view/product/view


define([
    'ko',
    'uiComponent'
], function (ko, Component) {
    'use strict';
    return Component.extend({
        initialize: function () {
            //initialize parent Component
            this._super();
            this.qty = ko.observable(this.defaultQty);
        },
        decreaseQty: function () {
            var newQty = this.qty() - 1;
            if (newQty < 1) {
                newQty = 1;
            }
            this.qty(newQty);
        },
        increaseQty: function () {
            var newQty = this.qty() + 1;
            this.qty(newQty);
        }
    });
});

This JavaScript function is designed to handle quantity changes. When triggered by an event, it checks the value of the event target and performs either an increase or decrease in the corresponding quantity value. It uses jQuery for DOM manipulation and assumes a specific HTML structure with input elements.
3-Create a catalog_product_view.xml file on the path.
    app/code/Esparksinc/QtyCounterProductPage/view/frontend/view/frontend/layout

And paste this code into it:


<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceBlock name="product.info.addtocart">
	   <action method="setTemplate">
	       <argument name="template" xsi:type="string">Esparksinc_QtyCounterProductPage::catalog/product/view/addtocart.phtml</argument>
	   </action>
       </referenceBlock>
       <referenceBlock name="product.info.addtocart.additional">
	   <action method="setTemplate">
	       <argument name="template" xsi:type="string">Esparksinc_QtyCounterProductPage::catalog/product/view/addtocart.phtml</argument>
	   </action>
       </referenceBlock>

   </body>
</page>

Run these commands:`

php bin/magento setup:upgrade 

See the result on product page: