jQuery validation: only numbers and decimal points are allowed to be entered
In web development, it is often necessary to verify the content entered by the user, especially when it comes to numerical input. It is often necessary to restrict users to input numbers and decimal points. This article will introduce how to use jQuery to achieve this function and provide specific code examples.
During the development process, sometimes users are required to enter only numbers and decimal points, such as amount input boxes, quantity input boxes, etc. In order to ensure the accuracy of the data and the standardization of the format, we need to limit user input.
We can use jQuery combined with regular expressions to limit user input. First, we need to determine whether the characters entered by the user meet the requirements in the keypress event of the input box. If they do not meet the requirements, block the default event. Then, in the blur event of the input box, we can further process the content entered by the user to ensure that the input content meets the requirements.
The following is a simple example code that implements the restriction that only numbers and decimal points are allowed to be entered in an input box:
<!DOCTYPE html> <html> <head> <title>jQuery validation: restrict input to numbers and decimal points</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <input type="text" id="numberInput" placeholder="只能输入数字和小数点"> <script> $(document).ready(function(){ $('#numberInput').keypress(function(event){ var charCode = (event.which) ? event.which : event.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { event.preventDefault(); } else { return true; } }); $('#numberInput').blur(function(){ var inputValue = $(this).val(); var newValue = inputValue.replace(/[^0-9.]/g, ''); $(this).val(newValue); }); }); </script> </body> </html>
In this code , we first introduced the jQuery library and created an input box with the id numberInput. In the ready event, we monitor the keypress event of the input box to determine whether the input content meets the requirements; in the blur event, we further process the input content to remove characters that do not meet the conditions.
Through the above code examples, we can limit the user input content and ensure that the input content meets the requirements. In actual development, the code can be appropriately modified and adjusted according to specific needs to meet the needs of different scenarios. I hope this article is helpful to you, thank you for reading!
The above is the detailed content of jQuery validation: restrict input to numbers and decimal points. For more information, please follow other related articles on the PHP Chinese website!