我正在使用简单的减号/加号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