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 name
attribute of an input
element is not the same as an id
attribute. Either
<input name="username" type="text" size="16" onkeyup="lookup(this.value);" onblur="fill();"/>
should be
<input id="username" name="username" type="text" size="16" onkeyup="lookup(this.value);" onblur="fill();"/>
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 fill
function. 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:
$.post("php/rpc.php", {queryString: username}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data)
// find list elements and attach the event handler
.find('li').click(function() {
// this removes the need to pass in any arguments:
// just use the text of the list element
var val = $(this).text();
$('#username').val(val);
// as @SLaks notes, better a function than a string here
setTimeout(function() {
$('#suggestions').hide();
}, 200);
});
}
});
This removes the need for two functions, and makes the HTML you load with AJAX simpler, since you can just load
<li>user1</li>
<li>user2</li>
See http://jsfiddle.net/nrabinowitz/WNJnc/3/ for a full working example of this code.
精彩评论