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,732
  • 4
  • 18
  • 30

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
  • 71,634
  • 16
  • 123
  • 171
2

Just use keyup instead of keypress.

Prisoner
  • 26,783
  • 10
  • 71
  • 99