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: /
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/oxpy96g9/
Share Improve this question edited Dec 22, 2015 at 2:18 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Dec 21, 2015 at 16:05 noclistnoclist 1,8294 gold badges33 silver badges76 bronze badges 7-
The 'lag' is unavoidable as the
keyup
event doesn't fire until the key is released and the value is added to the input field. – Rory McCrossan Commented Dec 21, 2015 at 16:06 - 1. A slowdown is introduced through jQuery 2. A slowdown is introduced through repeated variable declaration 3. A slowdown is introduced through firing up the JavaScript Regex machine 4. Your code runs AFTER the user releases the key, which looks like a slowdown. All in all, you've written a mess. – Andrue Anderson Commented Dec 21, 2015 at 16:07
-
3
Try listening to the
input
event instead...$('#ssn').on('input', function () { ... });
– Josh Crozier Commented Dec 21, 2015 at 16:07 - maybe just use keydown() ? api.jquery./keydown – brandelizer Commented Dec 21, 2015 at 16:09
- If you don't care about any of the previous points, try hooking keyup and keydown both, that might cause the visualization you're looking for. – Andrue Anderson Commented Dec 21, 2015 at 16:11
1 Answer
Reset to default 10Converting my ment 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, '');
});