0

I'm trying to disable the minus so that the value can not be below zero. So I would like to add some sort of disable when value is <= 0

    $("#dynamicContent").on("click", ".qtyplus, .qtyminus", function (e) {
    e.preventDefault();
    var $input  = $(this).closest("div.dynamicWrapper").find(".qty");
    var currentVal = parseInt($input.val());

    if (!isNaN(currentVal)) {
        $(this).hasClass("qtyplus") ? $input.val(currentVal + 1) : $input.val(currentVal - 1);
    } else {
        $input.val(0);
    }
});

I thougt below code would do it. But it didnt

if (currentVal == 0)
{
$('#qtyminus').attr('disabled',true);
} else{
$('#qtyminus').attr('disabled',false);
}
Andreas
  • 183
  • 1
  • 9
  • 1
    try `$("#qtyminus').attr('disabled', 'disabled');` – Jo E. Oct 22 '15 at 23:25
  • Possible duplicate of [Disable/enable an input with jQuery?](http://stackoverflow.com/questions/1414365/disable-enable-an-input-with-jquery) – Jo E. Oct 22 '15 at 23:26
  • And change `if (currentVal == 0)` to `if (currentVal <= 0)` so that negative values will still continue to disable the button. – Jo E. Oct 22 '15 at 23:28
  • Thing is. that the check is done after the click. So if the value is zero. The new value will be -1 and the button will be disabled. I would need to somehow disable the button and exit the remaining code somehow – Andreas Oct 22 '15 at 23:34
  • Found out that I should use `$('#qtyminus').attr('disabled',true);`->`$('#qtyminus').prop('disabled',true);` But still ahve the issue with the click-event. – Andreas Oct 22 '15 at 23:37
  • 1
    Your `.on()` call uses the class `.qtyminus`. But your code to disable the button uses the ID `#qtyminus`. So is it a class or ID? – Barmar Oct 22 '15 at 23:37

1 Answers1

0

Ok, I sorted it out. But it's not pretty.

Issue was that currentVal was not increased/decreased yet as that was done down in the code. So I added a new var currentVal2, that if currentVal <= 0 disable the button and increase + 1.

So now the button will not go below zero. But I do think that I could have an different approach.

    $("#dynamicContent").on("click", ".qtyplus, .qtyminus", function (e) {
    e.preventDefault();
    var $input  = $(this).closest("div.dynamicWrapper").find(".qty");
    var currentVal = parseInt($input.val());
    var currentVal2 = 0

    if (currentVal <= 0) // As qty is not changed yet. Increase currentVal + 1 and then disable the button 
    {
        $('.qtyminus').prop('disabled',true);
        currentVal2 = currentVal + 1;
    } else{
        $('.qtyminus').prop('disabled',false);
        currentVal2 = currentVal;
    }

    if (!isNaN(currentVal)) {
        $(this).hasClass("qtyplus") ? $input.val(currentVal + 1) : $input.val(currentVal2 - 1);
    } else {
        $input.val(0);
    }
    });
Andreas
  • 183
  • 1
  • 9