Jquery keypress immediately gets the value

I want to get the contents of an input window using jquery.keypress, and I saw the answer here . But this does not work as I need.

HTML looks like this:

<input type="text" id="foo" size="15" maxlength="50"> 

The jquery code is as follows:

 $("#foo").keypress (function (e) { alert ($(this).val()); }); 

So now I have an input field. I type "a". My warning is empty, because the handler retrieves the PREVIOUS "#foo" content. Now, if I type "b", the warning will have "a" instead of "ab" and so on. Take a look at the jsfiddle link and you will see where my problem is.

+4
source share
2 answers

It's impossible. The keypress event is fired before the letter is placed in the input field. Try setting a timeout or using the keyup event.

+5
source

Just use keyup instead of keypress .

+2
source

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


All Articles