Home » jQuery method to force numeric input on element with cmd and ctrl actions to allow select all and page refresh

jQuery method to force numeric input on element with cmd and ctrl actions to allow select all and page refresh


This is just a simple jQuery method to force numeric input on an <input> element. It allows backspace, tab, delete, arrow keys, numbers, numpad numbers, home, end, period, and CMD or CTRL key combinations for select all, copy, paste, etc. It took awhile to figure out all of these character code exceptions and combine them into one friendly method that doesn’t discriminate against Mac or Windows users. If I missed something, please feel free to comment!

Add this prototype method somewhere above where you use the method:

And then you can use it like this to apply it to all elements with class=”numeric”:

Alternatively you can add a method that only allows alpha characters like so:

And then you can use it like this to apply it to all elements with class=”alpha”:

Some of you will inevitably complain about this not allowing spaces and such, but don’t worry, all you have to do is add key == 32 || to the front of the return on these methods to allow spaces. You’ll have to tailor this to accept the characters that you want to accept. Feel free to post comments if you have any issues. For the sake of this tutorial I’m also going to start including a map of characters that are commonly checked for (either to prevent or allow) for your reference. This list will grow/change over time:

 

Leave a Reply

Your email address will not be published. Required fields are marked *