I am trying to create an MS-Dos emulation window with jquery and ajax. It works well, but when I type a word or press Enter, the script is one character too late on the display (the first time it is pressed, the character does not appear, and for each subsequent keystroke it shows the previous character entered by the user, not the current one).
Here is a simplified version of my script:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/terminal.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#cursor').css('left','0px');
$('#field').focus();
$('#field').keydown(function(event)
{
request=$(this).val();
count=$(this).val().length;
$("#instruct").html(request);
if (event.which == 13)
{
event.preventDefault();
request=request.replace(/\n/g, "");
$.ajax({
type: "POST",
url: "scripts/ajax/terminal.php",
data: {command:request},
success: function(response)
{
if(response !='')
{
$('#log').append("<li class='user'>--- ><span>"+request+"</span></li>");
$('#log').append("<li class='sys' >SYS ><span>"+response+"</span></li>");
$('#field').val('');
}
}
});
}
});
});
</script>
</head>
<body>
<ul id="log">
<li class='sys'>Sys ><span>Identification required</span></li>
</ul>
<ul id="realtime">
<li id="live-space">
<span class="user-line">--- ></span>
<textarea type="text" id="field"></textarea>
<div>
<span id="instruct"></span><div id="cursor">_</div>
</div>
</li>
</ul>
</body>
</html>
I am sure that "keyDown" is launched when it is needed, because when I change this
$("#instruct").html(request);
in that
$("#instruct").html(request+'x');
... "x" will appear immediately after the first keystroke, while the contents of the "request" will be delayed until the next keystroke (for example, if I type "a", I will see only "x" and When I immediately type "b", I see an "ax", etc.).
, , keydown, , .
?
.