views:

60

answers:

4

I got:

$(someTextInputField).keypress(function() {
  alert($(this).val());
});

Now the alert always returns the value BEFORE the keypress (e.g. the field is empty, I type 'a' and the alert gives me ''. Then I type 'b' and the alert gives me 'a'...). But I want the value AFTER the keypress - how can I do that?

Background: I'd like to enable a button as soon as the text field contains at least one character. So I run this test on every keypress event, but using the returned val() the result is always one step behind. Using the change() event is not an option for me because then the button is disabled until you leave the text box. If there's a better way to do that, I'm glad to hear it!

+6  A: 

Change keypress to keyup:

$(someTextInputField).keyup(function() {
  alert($(this).val());
});

keypress is fired when the key is pressed down, keyup is fired when the key is released.

Hooray Im Helping
Thanks, you guys are great!
werner5471
+3  A: 

Hi,

instead of keypress, use keyup.

Grz, Kris.

XIII
A: 
Pointy
A: 

You may want to hook up an onchange event handler instead of using any of the key events.

$(someTextInputField).change(function() {
    alert($(this).val());
});

Using Edit > Paste or a Right-Click then Paste will fire a change event, but not a key event. Note some browsers may simulate a key event on a paste (though I don't know of any) but you can't count on that behavior.

Stephen P