Domanda

I have an html page with a form text input that has a onkeydown attribute, like so:

<DOCTYPE !html>
<html>

<head>
<title>Lookup User</title>
</head>
<body>
<form method="POST">
<strong>Last Name: </strong><input type="text" id="lname" onkeydown="lookup_user(this.value)" />

</form>
<span id="test"></span>
<script type="text/javascript" src="lookup_user.js"></script>
</body>
</html>

The page makes asynchronous requests to a server to searchup the user as the keys are being downed. The javascript file is

function lookup_user (lname) {

var xmlhttp;

if (lname=='') {
    document.getElementById('lname').innerHTML = '';
    return;
}

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
}
else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}



// generally preferred to place onreadystatechange before open so that it detects readyState 0-4 instead of 1-4
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("test").innerHTML = xmlhttp.responseText;

    }
}

xmlhttp.open('POST', 'lookup_user.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('lname='+lname);



}

This works almost fine, except for the fact that it doesn't detect the first keydown.

For example, if in the input form, I type in 'D', it doesn't search up the user. When I type in the second character, it searches up the characters before the second character, not including the second character. If I want to look up "Daisy", and type in "Daisy" into the input box, it searches up "Dais". Only when I down another key does it lookup "Daisy".

Why is this?

È stato utile?

Soluzione

The onkeydown event is working properly.

When a key is pressed, the events are fired in the following sequence; keydown, keypress, keyup.

The onkeydown event is fired after the key press but before the character is put into the DOM.

Since the character has not been put into the DOM when the event is fired your form text input will not have that character inside of it.

For example: the onkeydown event can be used to restrict characters from being inputted into your form.

On the other hand: the onkeyup event is fired after the user has released the key and after the DOM has been modified.

Perhaps the onkeyup event is better suited for your application.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top