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