2

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?

3 Answers 3

4

Try .keyUp() that may fix it.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Try this:

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

http://jsbin.com/ibido3/edit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.