4

I want to get the contents of an input box using jquery.keypress and I saw an answer here. But that doesn't work as I need it to.

The HTML looks like this:

<input type="text" id="foo" size="15" maxlength="50">

The jquery code looks like this:

$("#foo").keypress (function (e) {
    alert ($(this).val());
});

So now I have an input box. I type "a". My alert is blank since the handler is retrieving the PREVIOUS contents of '#foo'. Now if I type 'b', the alert will have "a" instead of "ab" and so on. Have a look at this jsfiddle link and you will see where my problem lies.

Community
  • 1
  • 1
gdanko
  • 1,922
  • 4
  • 20
  • 31

2 Answers2

5

This is not possible. The keypress event is triggered before the letter is put in the input box. Try setting a timeout or using the keyup event.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
2

Just use keyup instead of keypress.

Prisoner
  • 27,391
  • 11
  • 73
  • 102