Home > Web Front-end > JS Tutorial > How Can I Restrict an HTML Text Input to Only Accept Numeric Keystrokes?

How Can I Restrict an HTML Text Input to Only Accept Numeric Keystrokes?

Linda Hamilton
Release: 2024-12-18 07:33:10
Original
999 people have browsed it

How Can I Restrict an HTML Text Input to Only Accept Numeric Keystrokes?

Can an HTML text input be restricted to only allowing numeric keystrokes?

The quick answer is yes, you can use the JavaScript function setInputFilter() to achieve this. The function takes three arguments, the textbox element, the input filter function, and the error message.

The input filter function is a function that takes a value as input and returns true if the value is valid or false if it is not valid. In this case, you would want the filter function to return true if the value is a digit (possibly with a decimal point).

Here is an example of an input filter function that would allow only digits and the '.' character:

function inputFilter(value) {
  return /^\d*\.?\d*$/.test(value);
}
Copy after login

Once you have defined the input filter function, you can use it to install an input filter on your textbox element using the following code:

setInputFilter(document.getElementById("myTextBox"), inputFilter, "Only digits and '.' are allowed");
Copy after login

The setInputFilter() function will apply the input filter to the specified textbox element. Any invalid characters that are typed into the textbox will be rejected and the error message will be displayed.

Note: It's important to not rely solely on client-side validation to prevent users from entering invalid characters. You should always validate the user input on the server-side as well.

The above is the detailed content of How Can I Restrict an HTML Text Input to Only Accept Numeric Keystrokes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template