onkeyup event JavaScript
-
28-09-2019 - |
Question
Here is my code :
function search_buddy()
{
$.post("num.php",function (ret){
num=ret;
});
$("#Layer7").html(num);
}
</script>
<div id="Layer8">
Find a buddy :
<input type="text" id="search" onkeyup="search_buddy()"/> :
</div>
Now,when i enter one character into the text box with id=search, the function search_buddy doesn't seem to get triggered. Whereas, if i enter two characters or more,the function works perfectly.Why is this happening ?
Solution
Best resource on DOM events: http://www.quirksmode.org/dom/events/keys.html
It looks like your event handler "search_buddy" fires an AJAX request, which is asynchronous. The rest of the function runs in parallel with the AJAX request, so "num" is undefined before the $.post returns.
// num is undefined here... unless your network has 0 latency
$("#Layer7").html(num);
You need to wrap this code (pasted above) in a callback function. It appears to be parameter number 3: http://api.jquery.com/jQuery.post/
Untested, but best guess:
function search_buddy() {
$.post("num.php", function (ret) {
num=ret;
$("#Layer7").html(num);
});
}
Here are some modifications to help you understand:
function search_buddy() {
alert("before the $.post execution");
$.post("num.php", function (ret) {
num=ret;
$("#Layer7").html(num);
alert("$.post callback");
});
alert("immediately after the $.post execution");
}
Note: "alert" will halt all JavaScript processing so you will be able to see what events occur when.