2016-01-13 22 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