8

I have a textbox where a user can only enter numeric data. I'm using the following function on keyup of the textbox:

$('#ssn').keyup(function () {
    var val = this.value.replace(/\D/g, '');
    this.value = val;
});

The problem I'm running into is the lag when the user keys up on a restricted key, the character displays for a moment before it's replaced with the empty string. And holding down a key will display a stream of characters in the box until the key is released. Is there a way to prevent this behavior? I've tried different keyboard events like keydown or keypress and they didn't seem to behave any better. Here is a fiddle of the problem: https://jsfiddle.net/oxpy96g9/

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
noclist
  • 1,659
  • 2
  • 25
  • 66

1 Answers1

10

Converting my comment to an answer

Rather than listening to the keyup event, listen to the input event so that the event is fired when the value changes rather than when the key is released:

Updated Example

$('#numbers').on('input', function() {
  this.value = this.value.replace(/\D/g, '');
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Oh wait. I tried this in jsfiddle, but apparently it was lagging, so it didn't process my click on "run" button after I've edited it to check :D – nicael Dec 21 '15 at 16:26