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);
}
});
});
如何设置此框的限制?我不想拥有超过100的数量,所以如果用户继续按下+按钮,当它达到100时的数量应该停止增加。
if(currentVal == 100)
{
$('input[name=' + fieldName + ']').val(currentVal);
}
我不认为这是正确的,我需要一些帮助
修改:http://jsfiddle.net/laelitenetwork/puJ6G/ Jsfiddle就在这里
答案 0 :(得分:0)
在增量逻辑中执行:
if (!isNaN(currentVal) && currentVal <= 100) {
我认为这应该有用。
答案 1 :(得分:0)
我创造了一个可能对你有帮助的简单逻辑。由于您没有提供任何HTML,我制作了一个简单的结构(可能与您的不同):
<input type="text" name="field1" value="0" />
<button class="qty" type="button" data-func="plus" data-field="field1">+1</button>
<button class="qty" type="button" data-func="minus" data-field="field1">-1</button>
请注意:
data-
前缀,例如data-field
和data-func
。qty
类 - 我们可以看出以后点击了哪个按钮。这简化了选择器,还可以防止冗余代码块(每个按钮一个,可以轻松膨胀)。现在这里是jQuery逻辑:
$('.qty').click(function() {
var $t = $(this),
$in = $('input[name="'+$t.data('field')+'"]'),
val = parseInt($in.val()),
valMax = 100,
valMin = 0;
// Check if a number is in the field first
if(isNaN(val) || val < valMin) {
// If field value is NOT a number, or
// if field value is less than minimum,
// ...set value to 0 and exit function
$in.val(valMin);
return false;
} else if (val > valMax) {
// If field value exceeds maximum,
// ...set value to max
$in.val(valMax);
return false;
}
// Perform increment or decrement logic
if($t.data('func') == 'plus') {
if(val < valMax) $in.val(val + 1);
} else {
if(val > valMin) $in.val(val - 1);
}
});
非常简单,是吗?您甚至可以通过在达到阈值时禁用<button>
元素来增强我的示例,但由于您没有提及它,我认为这更像是一种噱头而非必要性。
请参阅此处的小提琴:http://jsfiddle.net/teddyrised/2aC5C/3/