marsupilam marsupilam - 6 months ago 24
jQuery Question

One-( keypress-)event-delay between javascript input and output

The following snippet reproduces the input text in the webpage using simple javaScript and jQuery.

I am wondering, though, how come there is a one character (or more precisely : one keystroke) latency between the input and the output

eg :

  1. I type 'abcde'

  2. the output is 'abcd'

  3. however if I press the Insert key, the ultimate 'e' prints.

My code :

<!doctype html>
<meta charset="utf-8">
<input type="text" name="enteredText" id="myTextInput" />

<p id="myTextOutput">

<script src=""></script>
$("#myTextInput").keypress(function( ){
var theText = $("#myTextInput").val();

$( "html" ).click(function( event ) {

var value = $("#myTextInput").val();



Any idea ? Thanks


You're grabbing the value before you've allowed the event to propagate up to where the text field has been updated. You can add an infinitesimal delay to get the full value:

$("#myTextInput").keypress(function( ){
    setTimeout(function() {
       var value = $("#myTextInput").val();
    }, 0);