views:

21

answers:

3

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?

+2  A: 

Try .keyUp() that may fix it.

MoDFoX
Silly me. That fixed it.
pessimopoppotamus
+1  A: 

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

Ryan Tenney
A: 

Try this:

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

http://jsbin.com/ibido3/edit

chum of chance