jquery限定文本框只能输入数字(整数和小数)
本文实例介绍了jquery限定文本框只能输入数字的详细代码,分享给大家供大家参考,具体内容如下
先来一段规定文本框只能够输入数字包括小数的jQuery代码:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="gb2312">
<title>毛票票</title>
<scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script>
<scripttype="text/javascript">
//文本框只能输入数字(包括小数),并屏蔽输入法和粘贴
jQuery.fn.number=function(){
this.bind("keypress",function(e){
varcode=(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{returncode>=48&&code<=57}
});
this.bind("paste",function(){returnfalse;});
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>
<inputtype="text"id="txt"/>
</body>
</html>
2、jQuery如何规定文本框只能输入整数:
有时候文本框的内容只能够是数字,并且还只能够是整数,例如年龄,你不能够填写20.8岁,下面就通过代码实例介绍一下如何实现此功能,希望给需要的朋友带来帮助,代码如下:
<html>
<head>
<metacharset="gb2312">
<title>蚂蚁部落</title>
<scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script>
<scripttype="text/javascript">
//文本框只能输入数字(不包括小数),并屏蔽输入法和粘贴
jQuery.fn.integer=function(){
this.bind("keypress",function(e){
varcode=(e.keyCode?e.keyCode:e.which);//兼容火狐IE
//火狐下不能使用退格键
if(!$.browser.msie&&(e.keyCode==0x8))
{
return;
}
returncode>=48&&code<=57;
});
this.bind("paste",function(){
returnfalse;
});
this.bind("keyup",function(){
if(/(^0+)/.test(this.value))
{
this.value=this.value.replace(/^0*/,'');
}
});
};
$(function(){
$("#txt").integer();
});
</script>
</head>
<body>
<inputtype="text"id="txt"/>
</body>
</html>
以上代码实现了我们的要求,文本框中只能够输入整数。
希望本文所述对大家学习jquery程序设计有所帮助。