Aillyn
Aillyn

Reputation: 23803

jQuery keypress() event listener

I am trying to execute a function every time a field changes. Just to get started, I am using a simple textarea and a div:

<div id="text"></div>
<textarea id="stuff"></textarea>

<script type="text/javascript">
    $("#stuff").keypress(function () {
        $("#text").text($("#stuff").val());
    });
</script>

This works, but it is always one character behind. If I type "Hello" on the textarea, the div will just say "Hell".

What am I doing wrong?

Upvotes: 2

Views: 1015

Answers (3)

chum of chance
chum of chance

Reputation: 6300

Try this:

<script type="text/javascript">
    $("#stuff").keyup(function () {
        $("#text").html($(this).val());
    });
</script>

http://jsbin.com/ibido3/edit

Upvotes: 0

Ryan Tenney
Ryan Tenney

Reputation: 1841

The keypress event fires before the textarea updates it's value based on the keypress that occurred, otherwise the handler wouldn't be able to cancel the event.

See here: http://jsfiddle.net/zDMbJ/ which arbitrarily cancels an event if the key pressed was 'A'.

Upvotes: 1

MoDFoX
MoDFoX

Reputation: 2134

Try .keyUp() that may fix it.

Upvotes: 4

Related Questions