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 ?
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.
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:
Here are some modifications to help you understand:
Note: “alert” will halt all JavaScript processing so you will be able to see what events occur when.