jquery limited text boxes can only enter Numbers (integers and decimals)

  • 2020-11-20 05:59:30
  • OfStack

This article introduces the jquery limited text box can only enter the number of detailed code, share for your reference, the specific content is as follows

First, the jQuery code that specifies that the text box can only enter Numbers, including decimals:


<!DOCTYPE html> 
<html> 
<head> 
<meta charset="gb2312"> 
<title> The home of the script </title> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
// Text boxes can only enter Numbers ( Including the decimal ) , and block input method and paste  
jQuery.fn.number=function(){
 this.bind("keypress",function(e){ 
 var code=(e.keyCode?e.keyCode:e.which); // Compatible with firefox  IE 
 // You can't use the backspace key in Firefox  
 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 text box can only enter integers:
Sometimes, the content of the text box can only be Numbers and integers. For example, age, 20.8 years old, cannot be filled in. The following is a code example to introduce how to achieve this function.


<html> 
<head> 
<meta charset="gb2312"> 
<title> The ant tribe </title> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
// Text boxes can only enter Numbers ( Not including decimals ) , and block input method and paste  
jQuery.fn.integer=function(){ 
 this.bind("keypress",function(e){ 
 var code=(e.keyCode?e.keyCode:e.which); // Compatible with firefox  IE 
 // You can't use the backspace key in Firefox  
 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>

The above code implements our requirement that only integers can be entered in the text box.

I hope this article has been helpful in learning jquery programming.


Related articles: