AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JavaScript

jquery限定文本框只能输入数字(整数和小数)

51自学网 http://www.wanshiok.com
jquery,文本框,数字,整数,小数

本文实例介绍了jquery限定文本框只能输入数字的详细代码,分享给大家供大家参考,具体内容如下

先来一段规定文本框只能够输入数字包括小数的jQuery代码:

<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title>wanshiok.com</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程序设计有所帮助。


jquery,文本框,数字,整数,小数  
上一篇:javascript正则表达式定义(语法)总结  下一篇:jQuery实现的鼠标滑过弹出放大图片特效