5

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?

Munez NS
  • 1,011
  • 1
  • 12
  • 31

7 Answers7

6

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

AyB
  • 11,609
  • 4
  • 32
  • 47
3

Use keypress event instead of keydown event.

saikiran.vsk
  • 1,788
  • 1
  • 10
  • 11
1

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

vogomatix
  • 4,856
  • 2
  • 23
  • 46
1

try this code,hope keyup will work

$('#input').on("keyup", function(){
        var city = $(this).val();
        console.log(city);
    });
WAQAS AJMAL
  • 279
  • 4
  • 16
1

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.

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

try this code,hope it will work for you

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

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

Vicky
  • 694
  • 1
  • 8
  • 23