2016-01-13 71 views
1

我正在使用简单的减号/加号jsfiddle在输入字段中添加或删除数字。然而,我正试图找出设置最大值的最佳方法,这意味着如果用户试图输入大于10的数字或使用了他们不能超过10的加号功能,那么实现这一点的最佳方法是什么?使用jQuery为输入字段添加最大值

jQuery(document).ready(function(){ 
// This button will increment the value 
$('.qtyplus').click(function(e){ 
    // Stop acting like a button 
    e.preventDefault(); 
    // Get the field name 
    fieldName = $(this).attr('field'); 
    // Get its current value 
    var currentVal = parseInt($('input[name='+fieldName+']').val()); 
    // If is not undefined 
    if (!isNaN(currentVal)) { 
     // Increment 
     $('input[name='+fieldName+']').val(currentVal + 1); 
    } else { 
     // Otherwise put a 0 there 
     $('input[name='+fieldName+']').val(0); 
    } 
}); 
// This button will decrement the value till 0 
$(".qtyminus").click(function(e) { 
    // Stop acting like a button 
    e.preventDefault(); 
    // Get the field name 
    fieldName = $(this).attr('field'); 
    // Get its current value 
    var currentVal = parseInt($('input[name='+fieldName+']').val()); 
    // If it isn't undefined or its greater than 0 
    if (!isNaN(currentVal) && currentVal > 0) { 
     // Decrement one 
     $('input[name='+fieldName+']').val(currentVal - 1); 
    } else { 
     // Otherwise put a 0 there 
     $('input[name='+fieldName+']').val(0); 
    } 
}); 

});

jsfiddle

回答

1

如果你在一个JS/jQuery的解决方案有兴趣,只需更换第11行:

if (!isNaN(currentVal) && currentVal < 10) { 
         ^~~~~~~~~~~~~~~~~~~^---------[Add this to line 11 

http://jsfiddle.net/zer00ne/snwxaLx7/

要将值保持到10,而不是重置为0,变更线16:

 $('input[name=' + fieldName + ']').val(10); 
              ^^-----[Change 0 into 10 

http://jsfiddle.net/zer00ne/v1pje44v/

+0

有没有办法让它到达10的地方,它只是呆在那里?而不是重置为0.此外,他们仍然可能输入自己的号码我想确保他们不能 – Lynx

+0

@Lynx查看更新。如果手动输入的数字大于10,则在blur,key,click或focus(在另一个元素上)等值将变为10。 – zer00ne

1

你不需要plusminus按钮来实现这一目标。 input类型numberminmax属性将为您做这个。

<input type='Number' name='quantity' value='0' class='qty' max="10" min="0" />

参考this fiddle如果你还是想要去按钮和防止用户超越

+0

这将是纯溶液。但是,浏览器支持似乎不足。我需要在较旧的浏览器上使用它。 – Lynx