Is there a quick way to set an HTML text input (<input type=text />
) to only allow numeric keystrokes (plus '.')?
Javascript – HTML text input allow only numeric input
htmljavascriptjquery
Related Topic
- Javascript – How to modify the URL without reloading the page
- Html – How to allow only numeric (0-9) in HTML inputbox using jQuery
- HTML 5: Is it
,
, or - Html – Change a HTML5 input’s placeholder color with CSS
- Html – Why does HTML think “chucknorris” is a color
- Html – How to reformat HTML code using Sublime Text 2
- Javascript – Why does the JavaScript code receive a “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error, while Postman does not
- Javascript – Is it possible to apply CSS to half of a character
Best Answer
Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.
JavaScript
Try it yourself on JSFiddle.
You can filter the input values of a text
<input>
with the followingsetInputFilter
function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):You can now use the
setInputFilter
function to install an input filter:See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!
TypeScript
Here is a TypeScript version of this.
jQuery
There is also a jQuery version of this. See this answer.
HTML 5
HTML 5 has a native solution with
<input type="number">
(see the specification), but note that browser support varies:step
,min
andmax
attributes.e
andE
into the field. Also see this question.Try it yourself on w3schools.com.