Reputation: 23803
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
Reputation: 6300
Try this:
<script type="text/javascript">
$("#stuff").keyup(function () {
$("#text").html($(this).val());
});
</script>
Upvotes: 0
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