Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the new value of a text field on keypress?

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?

like image 600
Stephen Sorensen Avatar asked Jan 19 '10 20:01

Stephen Sorensen


People also ask

What is the difference between keypress () and Keydown ()?

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.

What happens if you press any key in TextBox?

After running your Windows Forms form, when you press any key in the TextBox control , an "ok" message will be display.

Is keypress deprecated?

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.


2 Answers

this is easy, just use onkeyup instead of onkeypress

like image 91
john Avatar answered Oct 05 '22 23:10

john


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.

like image 26
Nate B Avatar answered Oct 06 '22 01:10

Nate B