I have the following jQuery code:
$("#someTextInputID").keydown(function(event){
console.log(event.keyCode);
console.log("input_box.val(): "+input_box.val());
console.log("input_box.val().length: "+input_box.val().length);
})
What puzzles me is that if I type in "750", three keyCodes are logged but I also get this in my console after having typed the string above:
input_box.val(): 75
input_box.val().length: 2
What happens then with the last character i.e. "0"?
Quite simple, the last key pressed is not in the
.valueof aninputuntil thekeyupevent.The order of events when pressing a key is:
keydown(fires at most once per key press, key is available inevent.which, but not in.value)keypress(fires at least once per key press (e.g. if you hold the key down), key is available inevent.which, but not in.value)keyup(fires at most once per key press, key is available inevent.which, and in.value)You can detect which key was pressed during the
keydownorkeypressphase by examining thewhichproperty of theEventobject, and using theString.fromCharCodemethod.Another useful trick you can employ is to use
setTimeout, but pass a value of0as the delay. A delay of0adds the callback to the back of the callstack, which delays the execution long enough for the.valueto update.: