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/小提琴在这里
发布于 2014-06-06 18:57:08
我创造了一个简单的逻辑,可能对你有帮助。由于您没有提供任何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/
发布于 2014-06-06 18:36:15
在增量逻辑中,请执行以下操作:
if (!isNaN(currentVal) && currentVal <= 100) {我觉得这应该管用。
https://stackoverflow.com/questions/24087221
复制相似问题