jQuery keypress .val() returns previous value after function runs

This is the normal behavior of javascript. The function you call on keypress is running before the the value itself is added.

Let me demonstrate it to you. When you do .preventDefault() on keypress, what will happen? The character will not be inserted. Would it be logic that the code behind add the character, then run over preventDefault() and remove the character? I don't think so, that's why the function run before adding the character.

It will work with .keyup() because the character is already added.

Hope that clarify a little bit!


I have checked the link. Use the 'keyup' event. It works. This is due to when you use the keydown or keypress event then the event function runs before the value of the input tag is updated because it is keydown. If you try the code by pressing the key for sometime then you will see the function runs immediately. But on keyup the function will run after the key is released and updated therefore.

Tags:

Jquery