JQuery catches a single character input value

I catch the value of the input field:

    $('#input').on("keydown", function(){
        var city = $(this).val();
        console.log(city);
    });

When I type 'n', the console returns nothing, I type 'ne', it returns 'n', type 'new' returns 'ne'.

Why is this happening?

+4
source share
7 answers

This does not catch up with him, he does what he should, that is, displays letters in the console when a key is pressed. The letter will appear in the input field only after the key has been issued, so you will see it the next time you press the key.

What you need is this . keyup () event:

$('#input').on("keyup", function(){

Demo

+4
source

Use the keypress event instead of the keydown event.

+2
source

, ,

$('#input').on("keyup", function(){
        var city = $(this).val();
        console.log(city);
    });
+1

keydown , . , , , .

, jQuery .which, key code. , , .

.keypress() .

+1

, ,

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

keyup, ,

  $('#input').on("keyup", function(){
        var city = $(this).val();
        console.log(city);
    });

,

0
source

As noted in my comment, the keydown event occurs when a key is pressed, but before the key value is added to the field. You might want to prevent the key from being added to the field or to implement some shortcuts, and this event makes it possible to do so.

For a more complete explanation, read the JQuery Keyboard Events section.

0
source

Source: https://habr.com/ru/post/1540669/


All Articles