I have a strange issue that I can't seem to figure out:
This keydown/keypress function only returns the previous value (i.e. first time returns nothing, second time returns first value, third time returns second value, etc...)
http://jsfiddle.net/ZRPfb/
Can someone enlighten me as to why keydown and keypress dont work, but keyup works??
$(".modal-body #rowDownload").unbind().on('keypress',function(){
var numRows = $(".modal-body #rowDownload").val();
// var numRows = $(this).val();
alert(numRows);
if (typeof numRows !== 'number') return;
});
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.
keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.
The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
Short answer
Use .keyup()
event instead
Here's why
This is the normal behavior of javascript. The function you call on keypress is running before 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 logical 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 runs before adding the character.
It will work with .keyup()
because the character is already added.
Hope this clarifies 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With