为jQuery数量增减按钮脚本添加最小数量触发逻辑
修改jQuery数量增减按钮脚本实现自定义逻辑
需求说明
- 点击
+按钮:- 若输入框当前值为0且
min属性值>0,直接将值设为min;若min=0,则按step值递增 - 后续点击按
step值递增,不超过max限制
- 若输入框当前值为0且
- 点击
-按钮:- 若当前值大于
min值,按step值递减 - 若当前值等于
min值,点击后直接设为0
- 若当前值大于
修改后的完整脚本
function wcqib_refresh_quantity_increments() { jQuery("div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)").each(function(a, b) { var c = jQuery(b); c.addClass("buttons_added"), c.children().first().before('<input type="button" value="-" class="minus" />'), c.children().last().after('<input type="button" value="+" class="plus" />') }) } String.prototype.getDecimals || (String.prototype.getDecimals = function() { var a = this, b = ("" + a).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); return b ? Math.max(0, (b[1] ? b[1].length : 0) - (b[2] ? +b[2] : 0)) : 0 }), jQuery(document).ready(function() { wcqib_refresh_quantity_increments() }), jQuery(document).on("updated_wc_div", function() { wcqib_refresh_quantity_increments() }), jQuery(document).on("click", ".plus, .minus", function() { var $qtyInput = jQuery(this).closest(".quantity").find(".qty"), currentVal = parseFloat($qtyInput.val()), maxVal = parseFloat($qtyInput.attr("max")), minVal = parseFloat($qtyInput.attr("min")), stepVal = $qtyInput.attr("step"); // 初始化默认值 currentVal = (!currentVal || isNaN(currentVal)) ? 0 : currentVal; maxVal = (isNaN(maxVal)) ? "" : maxVal; minVal = (isNaN(minVal)) ? 0 : minVal; stepVal = (stepVal === "any" || isNaN(parseFloat(stepVal)) || !stepVal) ? 1 : parseFloat(stepVal); if (jQuery(this).is(".plus")) { let newVal; // 处理+按钮逻辑 if (currentVal === 0 && minVal > 0) { newVal = minVal; } else { newVal = currentVal + stepVal; } // 限制最大值 if (maxVal !== "" && newVal >= maxVal) { newVal = maxVal; } $qtyInput.val(newVal.toFixed(stepVal.getDecimals())); } else { let newVal; // 处理-按钮逻辑 if (currentVal > minVal) { newVal = currentVal - stepVal; newVal = Math.max(newVal, minVal); } else if (currentVal === minVal) { newVal = 0; } else { newVal = 0; } $qtyInput.val(newVal.toFixed(stepVal.getDecimals())); } $qtyInput.trigger("change"); });
示例表单代码
<!-- min=300的示例 --> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <input type="number" step="50" min="300" max="" id="1234567" name="1234567" readonly value="0" title="Quantity" class="input-text qty text" size="6" pattern="" inputmode=""> <input type="button" value="+" class="plus"> </div> <!-- min=0的示例 --> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <input type="number" step="50" min="0" max="" id="7654321" name="7654321" readonly value="0" title="Quantity" class="input-text qty text" size="6" pattern="" inputmode=""> <input type="button" value="+" class="plus"> </div>
内容的提问来源于stack exchange,提问作者dabri
相关产品推荐
相关产品推荐

