如果达到数字输入最大/减去属性,则禁用加/减按钮

时间:2014-03-11 21:55:16

标签: javascript jquery wordpress woocommerce

我正在开展WooCommerce项目。对于那些不熟悉WooCommerce的人来说,它通过动态添加相应的+/-按钮来运行大量数字输入,以控制您添加到购物车的产品数量。我想要做的是在数字输入达到其maxmin属性时禁用+/-按钮。如果未设置maxmin属性,则min应默认为0,最大值为999.在页面加载时,如果输入的数字valuemin开始,或者max(如果未设置minmax,则为后备),应立即停用相应的按钮,而不等待.change()输入的数字被触发

HTML (添加了前置按钮)

<div class="quantity">
    <input type="number" step="1" max="20" name="" value="1" class="qty">
</div>

HTML (已添加帖子按钮)

<div class="quantity buttons_added">
    <input type="button" value="-" class="minus">
    <input type="number" step="1" max="20" name="" value="1" class="qty">
    <input type="button" value="+" class="plus">
</div>

WooCommerce JS

$("div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)").addClass('buttons_added').append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />');

$("input.qty:not(.product-quantity input.qty)").each(function () {
    var min = parseFloat($(this).attr('min'));

    if (min && min > 0 && parseFloat($(this).val()) < min) {
        $(this).val(min);
    }
});

$(document).on('click', '.plus, .minus', function () {

    var $qty = $(this).closest('.quantity').find(".qty");
    var currentVal = parseFloat($qty.val());
    var max = parseFloat($qty.attr('max'));
    var min = parseFloat($qty.attr('min'));
    var step = $qty.attr('step');

    if (!currentVal || currentVal == "" || currentVal == "NaN") currentVal = 0;
    if (max == "" || max == "NaN") max = '';
    if (min == "" || min == "NaN") min = 0;
    if (step == 'any' || step == "" || step == undefined || parseFloat(step) == "NaN") step = 1;

    if ($(this).is('.plus')) {
        if (max && (max == currentVal || currentVal > max)) {
            $qty.val(max);
        } else {
            $qty.val(currentVal + parseFloat(step));
        }
    } else {
        if (min && (min == currentVal || currentVal < min)) {
            $qty.val(min);
        } else if (currentVal > 0) {
            $qty.val(currentVal - parseFloat(step));
        }
    }

    $qty.trigger('change');
});

我的JS

$.fn.disableNumberButtons = function () {
    var value = this.val();

    var minus = this.prev();
    var minAttr = this.attr('min'); 
    var min = (minAttr) ? minAttr : 0;
    (value > min) ? minus.removeClass('is-disabled') : minus.addClass('is-disabled');

    var plus = this.next();
    var maxAttr = this.attr('max');
    var max = (maxAttr) ? maxAttr : 999;
    (value < max) ? plus.removeClass('is-disabled') : plus.addClass('is-disabled');
}

$('input.qty').each(function () {
    $(this).disableNumberButtons();
});

$('input.qty').change(function () {
    $(this).disableNumberButtons();
});

问题

如果我将input[type="number"]的值增加到3到10之间,则会禁用加号按钮。一旦我得到高于10的值,它就会重新启用它,直到值达到20 max属性的值,它应该被禁用。是什么给了什么?

现场演示:http://jsfiddle.net/galengidman/a4RjS/

0 个答案:

没有答案