I have this javascript/ jquery to list available users.
HTML:
<input name="username" type="text" size="16" onkeyup="lookup(this.value);" onblur="fill();"/>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="images/upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
jquery:
<script type="text/javascript">
function lookup(username) {
if(username.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("php/rpc.php", {queryString: ""+username+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#username').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
This gives a list of available usernames that you can type in.
example HTML:
<li onclick="fill('user1');">user1</li>
<li onclick="fill('user1');">user1</li>
But the fill function does not work. If I add alert('test') a popup shows up, so it works, but it does not fill out the input field username
The main bug here is that the
nameattribute of aninputelement is not the same as anidattribute. Eithershould be
or the jQuery selector referencing it should be
$("input[name='username']").The other possible bug – and it really depends on how you’re declaring the javascript – is whether the AJAX-loaded HTML can access the
fillfunction. One easy way to fix this, though you may lose out somewhat in performance if you’re loading a large number of list elements, is to assign the event handler in the callback function:This removes the need for two functions, and makes the HTML you load with AJAX simpler, since you can just load
See http://jsfiddle.net/nrabinowitz/WNJnc/3/ for a full working example of this code.