Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery catching input value one character late

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?

like image 877
Munez NS Avatar asked May 15 '14 10:05

Munez NS


3 Answers

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

like image 116
AyB Avatar answered Nov 16 '22 23:11

AyB


Use keypress event instead of keydown event.

like image 27
saikiran.vsk Avatar answered Nov 16 '22 23:11

saikiran.vsk


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

like image 1
vogomatix Avatar answered Nov 17 '22 00:11

vogomatix