Home > Article > Web Front-end > jquery realizes that the specified text box can only enter numbers
This time I will bring you jquery to realize that only numbers can be entered into the specified text box. jquery can only input numbers into the specified text box. What are the precautions?The following is a practical case, let's take a look.
First, let’s start with a jQuery code that stipulates that the text box can only enter numbers including decimals:
<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title>PHP</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. How jQuery stipulates that the text box can only enter integers:
Sometimes the content of the text box can only be numbers, and it can only be integers. For example, for age, you cannot fill in 20.8 years old. The following is an example of how to implement this function through code . I hope it can help those who need it. Friends bring help, the code is as follows:
<html> <head> <meta charset="gb2312"> <title>1</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>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
Jquery Mobile custom button icon steps detailed explanation
Set multi-line text box [textarea] automatically Generate height
The above is the detailed content of jquery realizes that the specified text box can only enter numbers. For more information, please follow other related articles on the PHP Chinese website!