-3

We use the following code to change the input number value, using button up and down.

But when we clicking the increase or decrease button, it also submits the form.

How can we prevent it from submitting the form?

HTML:

<form  action="url" method="post" id="product_addtocart_form" novalidate="novalidate">
    <div class="field qty">
        <div class="control quantity">
            <input type="number"
                   name="qty"
                   id="qty"
                   min="1"
                   size="number"
                   value="<?= $block->getProductDefaultQty() * 1 ?>"
                   title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
                   class="input-text qty"
                   data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                   />
            <div class="quantity-nav"><button class="quantity-button quantity-up"><i class="far fa-angle-up"></i></button><button class="quantity-button quantity-down"><i class="far fa-angle-down"></i></button></div>
        </div>
    </div>
</form>

jQuery:

        <script>
            require(['jquery'], function ($) {
                $('.quantity').each(function() {
                  var spinner = $(this),
                    input = spinner.find('#qty'),
                    btnUp = spinner.find('.quantity-up'),
                    btnDown = spinner.find('.quantity-down'),
                    min = input.attr('min'),
                    max = input.attr('max');
            
                  btnUp.click(function() {
                    var oldValue = parseFloat(input.val());
                    if (oldValue >= max) {
                      var newVal = oldValue;
                    } else {
                      var newVal = oldValue + 1;
                    }
                    spinner.find("#qty").val(newVal);
                  });
            
                  btnDown.click(function() {
                    var oldValue = parseFloat(input.val());
                    if (oldValue <= min) {
                      var newVal = oldValue;
                    } else {
                      var newVal = oldValue - 1;
                    }
                    spinner.find("#qty").val(newVal);
                  });
            
                });
            });
        </script>
JGeer
  • 1,768
  • 1
  • 31
  • 75
  • 2
    _“How can we prevent it from submitting the form?”_ - by simply telling it that these `button` elements are not supposed to be _submit_ buttons - `type="button"` – CBroe Jun 23 '21 at 12:04
  • @CBroe, thanks! Quite stupid I did not saw that, problem solved! – JGeer Jun 23 '21 at 12:07
  • change button type from adding type="button" , your code will work fine – Milan Jun 23 '21 at 12:25

2 Answers2

0

Just use the type attribute within button tag.<button type="button" class="quantity-button quantity-up">

0

change button type from adding type="button" , your code will work fine

Milan
  • 46
  • 7