Allow Only Numeric Input in a Textbox with JQuery

When creating any sort of javascript or jQuery based numeric calculator or other type of form, you may need to make sure that you allow only numeric input in one or more fields to get proper results. I’ve seen people try and write in commas for really large numbers and even just enter accidental alphabetic input that they didn’t notice. This unexpected input can break math formulas that you may have in place. I’ll go over an easy to implement code snippet that fixes this problem before submission by restricting the input allowed.

How to Allow Only Numeric Input

What we will do is bind to the “keydown” action of the keyboard and evaluate each keypress before allowing it to either execute or not. We can identify each keyboard key with the assigned key codes. You can use this little keycode tool to check out the different key codes for each keyboard key. Regular numeric input ends at number 57 with most items prior to that being non-input navigational keyboard elements like arrow keys. We do make an exception and disallow number 32, which is the space key. There are also the number keypad keys that fall within the numbers 96 to 105 (the ones enabled/disabled with num lock), which I also added into this snippet. So this snippet overall allows the input of numbers from the top number bar of your keyboard along with the number keypad pad on the side.

Implementation

You can include this snippet at the bottom of your file with your other javascript. Obviously just make sure you have jQuery included as well. The only customization you will need to make to this code for it to work is to link it to your specific form fields that need it. In this example I am using the selector “input.numbersonly”. This would apply the numeric input restriction functionality to any input field with the “numbersonly” class added to it.
Example:
<input name="annualincome" size="12" type="text" class="numbersonly" />

You could also add the “numbersonly” class to your desired input fields to use this snippet as is, or you could change the selector in this snippet to match your existing inputs. Either way works just fine.

Modifications

You can modify the basic concept of this snippet to restrict the input on any text field to whatever you’d like. You could add in the allowance of decimal points, you could switch it around to only allow alphabetical characters, or you could even drive people crazy by disallowing a certain couple select letters and make them think their keyboard is broken. Whatever your plan, you just need to make the keycodes that you want to disallow return false and make the ones you want to allow return true within the keydown function.

Speak Your Mind

*