jQuery: Stop decrementing textbox value if value equals 0

江枫思渺然 提交于 2019-12-23 03:49:04

问题


What I have:

I have a readonly textbox and two links. The first link increments the value of the textbox by 1 whereas the second link decrements the value by 1.

What I need:

I need the textbox value to stop decrementing at zero (I don't want negative numbers).

My code:

jQuery:

jQuery(".increment").on('click',function(){
    jQuery(this).next(".amount input").val(parseInt(jQuery(this).next(".amount input").val())+1);
});

jQuery(".decrement").on('click',function(){
    jQuery(this).prev(".amount input").val(parseInt(jQuery(this).prev(".amount input").val())-1);
});

Note: .next and .prev are used because I have multiple textboxes.

HTML:

<!--This block of code is occurs more than once.-->
<td class="amount">
    <a href="#" class="increment"></a>
    <input type="text" readonly="readonly" value="0" />
    <a href="#" class="decrement"></a>
</td>

A loose guess:

...with regards to decrementing...

// open onclick code here

    if (jQuery(this).prev(".amount input").val != "0"){

        // decrement code here

    }

// close onclick code here

Resources:

My working code is modelled on this Stack Overflow answer: https://stackoverflow.com/a/12209831/835950

...at which a fiddle exists for convenience: http://jsfiddle.net/iMaverick/S3PLG/2/


回答1:


Demo

$("#down").on('click',function(){
    var value = (parseInt($("#incdec input").val() , 10) - 1);
    $("#incdec input").val((value-1) < 0 ? 0 :(value -1));
});



回答2:


Almost:

$(document).ready(function() {
    var $textbox = $("#incdec input");

    $("#up").click(function(){
        var value = parseInt($textbox.val(), 10);

        $textbox.val(value + 1);
    });

    $("#down").click(function(){
        var value = parseInt($textbox.val(), 10);

        if (value > 0) {
            $textbox.val(value - 1);
        }
    });
});

HTML5 also includes an <input type="number"> element:

<input type="number" min="0" value="1" />


来源:https://stackoverflow.com/questions/16139247/jquery-stop-decrementing-textbox-value-if-value-equals-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!