I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5…9) 0-9.
How can I do this using jQuery?
htmljquerynumericvalidation
I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5…9) 0-9.
How can I do this using jQuery?
Best Answer
Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.
jQuery
Try it yourself on JSFiddle.
There is no native jQuery implementation for this, but you can filter the input values of a text
<input>
with the followinginputFilter
plugin (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
inputFilter
plugin to install an input filter:See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!
Pure JavaScript (without jQuery)
jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. 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.