(function($) {
$.fn.checkNumber = function(options) {// 自定义购物车商品数量,只能输入数字
var defaultOpt = {
max : null,
min : null,
showButton : true,
minusBtn : '-',
plusBtn : '+'
}
, opt = $.extend(defaultOpt, options)
, checkNumber = function(e) { // 限制输入,只能为数字
var currentKey = e.which;
var thisVal = parseInt(this.value || 0, 10);
if ((currentKey < 37 || currentKey > 40) && currentKey != 8
&& currentKey != 46) {
if (thisVal > opt.max || thisVal < opt.min) {
e.preventDefault();
return false;
} else {
if ((currentKey==57) && (currentKey == 105)) {
e.preventDefault();
return false;
}
}
}
};
this.each(function() {
var inputObj = $(this).css('ime-mode', 'disabled');
if (opt.showButton) {
// 减少
var minusBtn = $(opt.minusBtn).click(
function() {
var val = inputObj.val() || 0, thisVal = parseInt(
val, 10) - 1;
if (opt.min && thisVal < opt.min) {
return;
}
inputObj.val(thisVal).trigger(
"blur");
}); // 增加 plusBtn=
$(opt.plusBtn).click(function() {
var val = inputObj.val() || 0, thisVal = parseInt(val, 10) + 1;
if (opt.max && thisVal > opt.max) {
return;
}
inputObj.val(thisVal).trigger("blur");
});
inputObj.after(plusBtn).before(minusBtn);
}
inputObj.attr("data-ovalue", inputObj.val() || 0)
.keydown(checkNumber)
.keyup(function() {
var thisVal = parseInt(this.value || 0);
if (opt.min && thisVal < opt.min) {
this.value = opt.min;
return;
} else if (opt.max && thisVal > opt.max) {
this.value = opt.max;
return;
};
}).blur(function() {
if (typeof opt.onchange === "function") {
var oldVal = inputObj
.attr("data-ovalue"), newVal = this.value || 0, diff = parseInt(
newVal, 10)
- parseInt(oldVal, 10);
if (diff == 0)
return;
opt.onchange.call(this, newVal,
diff);
inputObj
.attr("data-ovalue", newVal);
}
});
});
};
})(jQuery);
$(function(){
var opt = {max : 1000,min : 0,showButton:true,minusBtn:'minusBtn',plusBtn:'plusBtn'};
$("#validNum").change(function(){
$("#validNum").checkNumber(opt);
});
});