I'm catching value of an input field:
$('#input').on("keydown", function(){
var city = $(this).val();
console.log(city);
});
When I type 'n' console returns nothing, I type 'ne' it returns 'n', type 'new' it returns 'ne'.
Why is this happening?
It's not catching it late, it's doing what it's supposed to, that is show the letters in console while the key is being pressed. A letter would appear in the input box only after the key has been released, which is why you see it on the next key press.
What you need is the .keyup() event:
$('#input').on("keyup", function(){
DEMO
Use keypress event instead of keydown event.
As my comment states, the keydown event occurs when the key is pressed but before the key value is added to the field. It is possible you may wish to prevent the key being added to the field or to implement some shortcuts, and this event is the opportunity to do so.
For a more complete explanation, read the JQuery Keyboard events section
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With