Reputation: 1011
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?
Upvotes: 5
Views: 1673
Reputation: 301
try this code,hope it will work for you
$("#input").keyup(function() {
console.log($(this).val());
});
Upvotes: 1
Reputation: 15393
The keydown event is sent to an element when the user first presses a key on the keyboard.To determine which key was pressed, examine the event object that is passed to the handler function.
While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows.
For catching actual text entry, .keypress()
may be a better choice.
Upvotes: 1
Reputation: 289
try this code,hope keyup will work
$('#input').on("keyup", function(){
var city = $(this).val();
console.log(city);
});
Upvotes: 1
Reputation: 5051
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
Upvotes: 1
Reputation: 704
You have to use keyup in order to get what you want
$('#input').on("keyup", function(){
var city = $(this).val();
console.log(city);
});
think this is what you want
Upvotes: 0
Reputation: 11675
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(){
Upvotes: 6