We have a html input with a increase and decrease button beside, to change the value into the input by clicking. Problem now is that the form directly submits after click.
We want to add a delay of 1 second, when the user stops clicking. We already tried the delay function, but we face the issue that this directly creates a delay of 1 second. So when the user is not ready clicking, after 1 second the form is still submitted.
We want to change that, so the form is only submitted after 1 second, after the user stops clicking.
How can we achieve that?
HTML:
<div class="product-cart-qty-item" data-th="<?= $block->escapeHtml(__('Qty')) ?>">
<div class="product-cart-qty-block">
<button type="button" id="<?= /* @escapeNotVerified */ $_item->getId() ?>-dec" class="decreaseQty"><i class="far fa-minus"></i></button>
<input id="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty"
name="cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]"
data-cart-item-id="<?= /* @escapeNotVerified */ $_item->getSku() ?>"
value="<?= /* @escapeNotVerified */ $block->getQty() ?>"
type="number"
size="4"
title="<?= $block->escapeHtml(__('Qty')) ?>"
class="input-text qty"
data-validate="{required:true,'validate-greater-than-zero':true}">
<button type="button" id="<?= /* @escapeNotVerified */ $_item->getId() ?>-upt" class="increaseQty"><i class="far fa-plus"></i></button>
</div>
</div>
jQuery:
$('#<?php echo $_item->getId();?>-upt, #<?php echo $_item->getId();?>-dec').on("click",function(){
var $this = $(this);
var ctrl = ($(this).attr('id').replace('-upt','')).replace('-dec','');
var currentQty = $("#cart-"+ctrl+"-qty").val();
if($this.hasClass('increaseQty')){
var newAdd = parseInt(currentQty)+parseInt(1);
$("#cart-"+ctrl+"-qty").val(newAdd);
$('form#form-validate').submit();
}else{
if(currentQty>1){
var newAdd = parseInt(currentQty)-parseInt(1);
$("#cart-"+ctrl+"-qty").val(newAdd);
$('form#form-validate').submit();
}
}
});
2
Answers
It’s hard to edit your code to make it work in an example because it has so much PHP mixed in it. However, here’s a simplified example with just a button you you click to increase a number and after a delay when stopped clicking it shows a message. I think you can adapt this into your code.
Basically on click you need to start a timer, and save it. On each click you also have to clear any previous timers and re-save the new timer to the same variable.
Basic debounce function using a timeout and clear it when user does another action
To make it with a reusable debounce method