检测输入数字jQuery的实际变化



我有一个表单,其中有一个加号和减号按钮来更改输入数字。如果这个数字达到最大值,它就不会再添加了。但问题是,尽管从技术上讲它没有被更改,但它仍然会触发更改事件。那样的话我该怎么办?

JQUERY:

var countdown;
jQuery(document).on('change', ".qty", function() {
var quantity = jQuery(this).val();
var maxquantity = jQuery(this).attr("max");
clearTimeout(countdown);
if (quantity == 0) {
if (confirm("really?")) {
// Running without a noticeable delay since the user confirmed their choice.
countdown = setTimeout(wauc_update_cart, 100);
}
} else if (quantity == maxquantity) {
console.log("max");
} else {
countdown = setTimeout(wauc_update_cart, 1000);
}
});
function wauc_update_cart() {
jQuery("[name='update_cart']").trigger("click");
console.log("meghivva");
}
//I CAN NOT EDIT THIS PART!
jQuery('.plus.button').on('click', function() {
var count = parseInt(jQuery('.qty').val());
var maxquantity = jQuery('.qty').attr("max");
var ujszam = 0;
if (count == maxquantity) {
var ujszam = maxquantity;
} else {
var ujszam = count + 1;
}
jQuery('.qty').val(ujszam).change();
});
jQuery('.minus.button').on('click', function() {
var count = parseInt(jQuery('.qty').val());
var ujszam = 0;
if (count == 0) {
var ujszam = 0;
} else {
var ujszam = count - 1;
}
jQuery('.qty').val(ujszam).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity buttons_added">
<label class="screen-reader-text" for="quantity_635fccb23107f">Test item 1</label>
<input type="button" value="﹣" class="minus button is-form">
<input type="number" id="quantity_635fccb23107f" class="input-text qty text" step="1" min="0" max="7" oldvalue="6" name="cart[ab21e63bd2a052ce9fe5dab95a189b62][qty]" value="5" title="Mny" size="4" placeholder="" inputmode="numeric" oldvalue="14">
<input type="button" value="﹢" class="plus button is-form">
</div>

如果我理解正确,您不想在达到最大值(本例中为7(并单击加号按钮后清除倒计时超时,对吧?

如果要防止这种情况,可以向count元素添加一个新属性,保存旧值。然后在change函数中,将当前值与旧值进行检查,只有当值不同时才执行倒计时。

var countdown;
jQuery(document).on('change', ".qty", function (e) {
var quantity = jQuery(this).val();
var oldValue = jQuery(this).attr("old-value");
if (oldValue !== quantity) {
jQuery(this).attr("old-value", quantity);
var maxquantity = jQuery(this).attr("max");
clearTimeout(countdown);
if (quantity == 0) {
if (confirm("really?")) {
// Running without a noticeable delay since the user confirmed their choice.
countdown = setTimeout(wauc_update_cart, 100);
}
}
else {
countdown = setTimeout(wauc_update_cart, 1000);
}
}
});
function wauc_update_cart() {
jQuery("[name='update_cart']").trigger("click");
console.log("meghivva");
}

最新更新