Home > Web Front-end > JS Tutorial > How Can I Restrict an HTML Text Input to Only Accept Numeric Values (and a Decimal Point)?

How Can I Restrict an HTML Text Input to Only Accept Numeric Values (and a Decimal Point)?

Linda Hamilton
Release: 2024-12-28 18:38:14
Original
939 people have browsed it

How Can I Restrict an HTML Text Input to Only Accept Numeric Values (and a Decimal Point)?

How can I set an HTML text input to only allow numeric input (plus '.')?

JavaScript

You can use the setInputFilter function to install an input filter:

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp.
}, "Only digits and '.' are allowed");
Copy after login

This function will restrict the input values of a text to the given inputFilter function. It supports Copy Paste, Drag Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error messages, and all browsers since IE 9.

Note: You must still do server-side validation for security!

The above is the detailed content of How Can I Restrict an HTML Text Input to Only Accept Numeric Values (and a Decimal Point)?. 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