jQuery based text box can only enter the number of decimal integer

  • 2020-12-07 03:57:50
  • OfStack

In practice, text boxes are sometimes only allowed to enter integers, but sometimes they can be more philanthropic. 1, you can enter floating-point numbers.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="https://www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){ 
$(".NumText").keyup(function(){ 
$(this).val($(this).val().replace(/[^0-9.]/g,'')); 
}).bind("paste",function(){ 
$(this).val($(this).val().replace(/[^0-9.]/g,'')); 
})
}); 
</script>
</head>
<body>
<input type="text" class="NumText"/>
</body>
</html>

The above code implements our requirements, the text box can only input integer or floating point numbers, the code is relatively simple and I won't go into more details here.

Here's how to use jquery to realize that text boxes can only enter integers:

Sometimes it is necessary to specify that the text box content can only be entered as an integer. Here is an example of a piece of code that can achieve this function for your friends.

The code is as follows:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="https://www.ofstack.com" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){ 
$(".NumText").keyup(function(){ 
$(this).val($(this).val().replace(/\D|^0/g,'')); 
}).bind("paste",function(){
$(this).val($(this).val().replace(/\D|^0/g,'')); 
})
}); 
</script>
</head>
<body>
<input type="text" class="NumText"/>
</body>
</html> 

Above code to achieve the desired requirements, the text box can only enter the integer, the following introduction 1 of its implementation process.

Code comments:

1.$(function(){}), when the document structure is fully loaded before executing the code in the function.
2.$(".NumText ").keyup(function(){}), register the keyup event handler for the text box.
3.$(this).val ($(this).val ().replace (/\D|^0/g,'), using regular expressions to replace non-numeric content with null via the replace() function.
4.bind("paste",function(){$(this).val($(this).val().replace(/\D|^0/g,'')); }), registered paste event handling is vague, of course, using a chain call here, which can prevent users from using ctrl+v mode copy paste.

The above code is relatively simple to write, some of the difficult points to you with comments, I believe it will be helpful to you.


Related articles: