First of all, please see this simple tutorial on more detail on input control filtering with JavaScript with better code:
http://www.javascripter.net/faq/keyboardinputfiltering.htm[
^].
Also, these are the very useful resources used to find out what to filter:
http://www.asquare.net/javascript/tests/KeyCode.html[
^],
http://unixpapa.com/js/testkey.html[
^].
Solution 1 gives you the right idea, but, unfortunately, does not solves the problem. It does filter out all except minus sign, decimal digits and backspace (important thing: 8). But on top of it, you need some validation anyway. This is because minus sign can be misplaced or added twice, or the number of digits can be too big, in other words, the input still can be invalid. Besides, you may need to additionally check up the data for some required range.
Therefore, you cannot get away without the validation. The best initial step of validation would be to actually parse the string into number. In addition to the validation, you will get the number itself, which you should use. Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt[
^].
Only now you got everything to deal with numeric input in your case.
—SA