What is the best way to restrict "number"-only input for textboxes?
I am looking for something that allows decimal points.
I see a lot of examples. But have yet to decide which one to use.
Update from Praveen Jeganathan
No more plugins, jQuery has implemented its own jQuery.isNumeric()
added in v1.7.
See: https://stackoverflow.com/a/20186188/66767
You dont see alphabets magical appearance and disappearance on key down. This works on mouse paste too.
I think this is a good way of solving this problem and it's extremely simple:
Example: JSFiddle
Scenarios covered
Most similar recommendations here fail at least one of these or require a lot of code to cover all these scenarios.
home
,end
, and thearrow
keys.delete
andbackspace
to be used at any index.keyup
event is not used.Scenarios failed
0.5
and deleting only the zero will not work. This can be fixed by changing the regex to/^[0-9]*\.?[0-9]*$/
and then adding a blur event to prepend a0
when the textbox starts with a decimal point (if desired). See this advanced scenario for a better idea of how to fix this.Plugin
I created this simple jquery plugin to make this easier:
Update
There is a new and very simple solution for this:
See this answer or try it yourself on JSFiddle.
jquery.numeric plugin
I've successfully implemented many forms with the jquery.numeric plugin.
Moreover this works with textareas also!
However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.
HTML 5
With wider support for the HTML 5 standard, we can use
pattern
attribute andnumber
type forinput
elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information aboutnumber
and other newer input types is available here.Other way to keep the caret position on the input:
Advantages:
Plunker: Demo working
I used this,with good results..
I just found an even better plug-in. Gives you much more control. Say you have a DOB field where you need it be numeric but also accepts "/" or "-" characters.
It works great!
Check it out at http://itgroup.com.ph/alphanumeric/.