I have a single form field and I need to be able to detect when the field changes and execute some additional code using the new value of the field. I only want to execute the code if the key pushed actually changes the value of the text box. Here's the solution I came up with.
function onkeypress(e) {
var value = this.value;
// do something with
}
function onkeyup(e) {
if ( e.which == 8 || e.keyCode == 46 ) { // delete or backspace keys
this.onkeypress(e);
}
}
There's just one problem though. onkeypress is fired before the field's value is updated, so when I grab the value, I'm getting the previous value. I would use keyup exclusively if I knew a way to test whether the key changed the value or not, but some characters (like the arrow keys) have no effect on the field's value.
Any ideas?
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.
After running your Windows Forms form, when you press any key in the TextBox control , an "ok" message will be display.
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.
this is easy, just use onkeyup instead of onkeypress
The way I do this is simply with a variable along the lines of prevValue
. At the end of the key press function, store the value in that variable, and only execute the function again if the value doesn't equal that previous value.
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