Search code examples
javascriptjquerykeyup

Input val() at keyup event is delayed


If you type two characters – e.g. the number '12' - quickly into an input field and log the val() at each keyup event, we get two keyup events but the val() is 12 (in my example) both times.

$(".myInput").keyup(function(e){
  console.log("val() = " + $(this).val());
});

Expected output when typing '12':

val() = 1
val() = 12

Observed output when typing '12':

val() = 12
val() = 12

Fiddle HERE.

Is there an inbuilt delay in updating val()? This feels like a bug but I see the same behaviour across Chrome, Safari and Firefox.


Solution

  • It's because you're pressing 2 before the keyup event for 1 has fired. It won't fire until you release the key, but you can type the next character before releasing the first. Since the input box then contains 12 before either keyup event fires, that's what val() reports back to you on both events.