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
HTML5 supports input type number with global browser support 88%+ according to CanIUse as of Oct 2015.
This is not JQuery related solution, but the advantage is that on mobile phones Android keyboard will be optimized for entering numbers.
Alternatively, it is possible to use input type text with new parameter "pattern". More details in HTML5 spec.
I think it is better than jquery solution, since in this question provided jquery solution do not support thousands separator. If you can use html5.
JSFiddle: https://jsfiddle.net/p1ue8qxj/
If you want to restrict input (as opposed to validation), you could work with the key events. something like this:
And:
This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.
You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.
Below is what I use to literally block the keystrokes. This only allows numbers 0-9 and a decimal point. Easy to implement, not a lot of code, and works like a charm:
The numeric() plugin mentioned above, doesn't work in Opera (you can't backspace, delete or even use the back or forward keys).
The code below in both JQuery or Javascript will work perfectly (and it's only two lines).
JQuery:
Javascript:
Of course this is for pure numeric input (plus backspace, delete, forward/back keys) only but can easily be changed to include points and minus characters.
This is a snippet I've just done (using a part of code by Peter Mortensen / Keith Bentrup) for an integer percent validation on a textfield (jQuery is required):
This code:
I hope this helps those in need.
Found a great solution here http://ajax911.com/numbers-numeric-field-jquery/
I just changed the "keyup" to "keydown" as per my requirement