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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 followinginputFilterplugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):You can now use the
inputFilterplugin to install an input filter:Apply your preferred style to input-error class. Here’s a suggestion:
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,minandmaxattributes.eandEinto the field. Also see this question.Try it yourself on w3schools.com.