我正在使用簡單的減號/加號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);
}
});
});
有沒有辦法讓它到達10的地方,它只是呆在那裏?而不是重置爲0.此外,他們仍然可能輸入自己的號碼我想確保他們不能 – Lynx
@Lynx查看更新。如果手動輸入的數字大於10,則在blur,key,click或focus(在另一個元素上)等值將變爲10。 – zer00ne