Skip to content
Advertisement

Why do I get wrong, doubled input value on keyup when typing fast?

$("#input").keyup(function(){
 console.log($(this).val());
})

When one is typing slowly “a” & “b” the above code will result in “a”, “b” in the console log. But the problem is when somebody does it quickly. The result then is “ab”, “ab”. It’s easier to repeat this situation with letters which are near on a keyboard e.g. “e” & “r”. How to avoid it?

Events keydown and keypress does not suffer from this problem of quick-typist, but they are also fire to early. Result: returned value of an input does not contain the last typed letter when they occur. Or maybe there is a way to get this last letter somehow?

Advertisement

Answer

Well, the problem is not really fast typing, but actually when the key up event happens. Consider this:

  • a is pressed
  • b is pressed
  • a is released
  • b is released

No matter how slowly this is done, you will not get the key up event until the first key is released. There is obviously no way around this, you can’t cause the key up event before the key is released.

If you just want the key that is pressed in a key press event, you can get it from the event object. Example:

$('#input').keypress(function(e){
  console.log(e.which);
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement