JavaScript

0 3109

jquery_bumper.sh-600x600
Today I decided to revisit how to best allow only numerics in a text field.  In the past, I have done this on the keydown event and matched against the key to see if that key that was pressed was allowed in the field.  This can then stop any unwanted keys from being allowed into the field.  Usually, it becomes a little bit of a headache because you do want to allow the user to use backspace, delete, arrows, decimal, hyphen, etc…  Then there is checking to make sure the hyphen can only be at the beginning and only allowing 1 decimal point, etc.  It can get to become quite the headache with all of the different things to look for.

I found a post on Stackoverflow and I was intrigued by one of the solutions using the keyup approach, test the data, and then remove any non numerics from it. There was some pretty nifty regex on there, but a lot of them still seemed to have problems allowing more than 1 decimal and the such. Someone had mentioned about just using jQuery.isNumeric(). I decided to write an example of how this could be done using the jQuery function.

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});

This will force the field to only contain numeric values. The one down side of doing it this way is that you see the non numeric char quickly appear and disappear. This is a great solution as long as that does not bother you.

Here is an example fiddle where you can see it in action.