JQuery: stop decrementing text field value if value is 0

What I have:

I have a read-only text box and two links. The first link increases the value of the text field by 1, while the second link decreases the value by 1.

What I need:

I need a text box value to stop decrementing to zero (I don't want negative numbers).

My code is:

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 several text fields.

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> 

Free guess:

... regarding decrement ...

 // open onclick code here if (jQuery(this).prev(".amount input").val != "0"){ // decrement code here } // close onclick code here 

Resources:

My working code is modeled by this response to a stack overflow: https://stackoverflow.com/a/4648772

... in which for convenience there is a script: http://jsfiddle.net/iMaverick/S3PLG/2/

+1
source share
2 answers

Demo

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

Nearly:

 $(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 the <input type="number"> element:

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

All Articles