需求:表单中输入1-100的正整数
方法一
html
<input type="text" class="number" maxNum="100">
js$(document).ready(function(){
$(".number").bind("keyup", function () { //粘贴事件
CheckNum(this);
});
})
function CheckNum(obj) { //验证整数
console.log('CheckNum已执行');
obj = $(obj);
var tmptxt = obj.val().replace(/\D/, ''); //利用正则表达式
var maxNum = $.trim(obj.attr("maxNum")); //最大值
console.log(parseInt(tmptxt),maxNum);
if (maxNum) {
if (parseInt(maxNum) >= parseInt(tmptxt)||isNaN(parseInt(tmptxt))){
if(parseInt(tmptxt)>=1){
obj.val(parseInt(tmptxt));
}else{
obj.val('1');
}
}else{
obj.val(parseInt(maxNum));
}
console.log(parseInt(tmptxt));
}
// obj.val(parseInt(tmptxt));
}
方法二
html
<input type="text" onkeyup="modifyQtyByEnterKey(event, this, '{{$item->rowId}}' )>
jsfunction modifyQtyByEnterKey(event, qtyInputTag, commodityId)
{
if(parseInt( event.keyCode) >=37 && parseInt( event.keyCode)<=40 ){
return ;
}
console.log(event);
qtyInputTag.value=qtyInputTag.value.replace(/\D/g,'');
var currentQty = $(qtyInputTag).val();
if(currentQty<=1){
qtyInputTag.value=1;
}else if(currentQty>100){
qtyInputTag.value=100;
}
if (event.keyCode == "13"){//enter
//enter時提交数据
}
}