本文实例介绍了jquery限定文本框只能输入数字的详细代码,分享给大家供大家参考,具体内容如下
先来一段规定文本框只能够输入数字包括小数的jQuery代码:
<!DOCTYPE html>
<html>
<head>
<meta charset=\"gb2312\">
<title>phpstudy</title>
<script type=\"text/javascript\" src=\"mytest/jQuery/jquery-1.8.3.js\"></script>
<script type=\"text/javascript\">
//文本框只能输入数字(包括小数),并屏蔽输入法和粘贴
jQuery.fn.number=function(){
this.bind(\"keypress\",function(e){
var code=(e.keyCode?e.keyCode:e.which); //兼容火狐 IE
//火狐下不能使用退格键
if(!$.browser.msie&&(e.keyCode==0x8)){return;}
if(this.value.indexOf(\".\")==-1){return (code >= 48 && code<= 57)||(code==46);}
else{return code >= 48 && code<= 57}
});
this.bind(\"paste\",function(){return false;});
this.bind(\"keyup\",function(){
if(this.value.slice(0,1) == \".\")
{
this.value = \"\";
}
});
this.bind(\"blur\",function(){
if(this.value.slice(-1) == \".\")
{
this.value = this.value.slice(0,this.value.length-1);
}
});
};
$(function(){
$(\"#txt\").number();
});
</script>
</head>
<body>
<input type=\"text\" id=\"txt\" />
</body>
</html>
2、jQuery如何规定文本框只能输入整数:
有时候文本框的内容只能够是数字,并且还只能够是整数,例如年龄,你不能够填写20.8岁,下面就通过代码实例介绍一下如何实现此功能,希望给需要的朋友带来帮助,代码如下:
<html>
<head>
<meta charset=\"gb2312\">
<title>蚂蚁部落</title>
<script type=\"text/javascript\" src=\"mytest/jQuery/jquery-1.8.3.js\"></script>
<script type=\"text/javascript\">
//文本框只能输入数字(不包括小数),并屏蔽输入法和粘贴
jQuery.fn.integer=function(){
this.bind(\"keypress\",function(e){
var code=(e.keyCode?e.keyCode:e.which); //兼容火狐 IE
//火狐下不能使用退格键
if(!$.browser.msie&&(e.keyCode==0x8))
{
return ;
}
return code >= 48 && code<= 57;
});
this.bind(\"paste\",function(){
return false;
});
this.bind(\"keyup\",function(){
if(/(^0+)/.test(this.value))
{
this.value = this.value.replace(/^0*/,\'\');
}
});
};
$(function(){
$(\"#txt\").integer();
});
</script>
</head>
<body>
<input type=\"text\" id=\"txt\" />
</body>
</html>
以上代码实现了我们的要求,文本框中只能够输入整数。
希望本文所述对大家学习jquery程序设计有所帮助。
本文地址:https://www.stayed.cn/item/4491
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我