In jquery, you can use the replace() method and regular expressions to set that only numbers can be filled in. The replace() method is used to replace a substring that matches the regular expression. When the filled content is not a number, it will not be filled in. Display, the syntax is "specify element object.val().replace(/[^\d]/g,"")".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
How to set jquery to only fill in numbers
Some input text boxes need to make some judgments. Only numbers can be entered. This judgment can be passed Regular expressions are used to judge. When the content entered by the user is not a number, it will not be displayed in the input text box. Let us take a look at how jq can set only numbers to be entered.
Syntax:
$('input').on('input propertychange', function(e) { var text = $(this).val().replace(/[^\d]/g, ""); $(this).val(text) })
Create a new html file.
Create an input box on the html file, and then set the size of the input box.
Code:
Introduce the jquery.min.js file.
Code:
Use regular expressions to determine users Every time you enter content, it will not be displayed if it is not a number.
Code:
<script> $(function(){ $(&#39;input&#39;).on(&#39;input propertychange&#39;, function(e) { var text = $(this).val().replace(/[^\d]/g, ""); $(this).val(text) }) }) </script>
Picture:
After saving the html file, open it in a suitable browser for testing, and it is found that the input is not a number The content cannot be displayed on the text box. As shown in the picture:
# Just copy and paste all the code into the new html file, and you can see the effect after saving.
All codes:
<script> $(function(){ $(&#39;input&#39;).on(&#39;input propertychange&#39;, function(e) { var text = $(this).val().replace(/[^\d]/g, ""); $(this).val(text) }) }) </script>
Recommended related video tutorials: jQuery video tutorial
The above is the detailed content of How to set jquery to only fill in numbers. For more information, please follow other related articles on the PHP Chinese website!