Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get jQuery .val() AFTER keypress event?

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!

like image 288
Jörg Brenninkmeyer Avatar asked Jun 17 '10 16:06

Jörg Brenninkmeyer


People also ask

How do you find out which key was pressed in jQuery?

To check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself. Then in bind() function check the keycode of pressed key whether it's value is 13 is not.

What is the difference between jQuery Change () and keypress () events?

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.

Which jQuery event occurs when key is pressed?

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).


1 Answers

Change keypress to keyup:

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

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

like image 119
Hooray Im Helping Avatar answered Sep 16 '22 12:09

Hooray Im Helping