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
No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7.
Samples results
Here is an example of how to tie the isNumeric() in with the event listener
Javascript Approach
jQuery Approach
UPDATE
The above answers are for most common use case - validating input as a number.
This code worked pretty good on me, I just had to add the 46 in the controlKeys array to use the period, though I don't thinks is the best way to do it ;)
I thought that the best answer was the one above to just do this.
but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)
I added in a simple change
this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.
You can use autoNumeric from decorplanit.com . They have a nice support for numeric, as well as currency, rounding, etc.
I have used in an IE6 environment, with few css tweaks, and it was a reasonable success.
For example, a css class
numericInput
could be defined, and it could be used to decorate your fields with the numeric input masks.adapted from autoNumeric website:
Just run the contents through parseFloat(). It will return
NaN
on invalid input.