Reputation: 535
This is a follow on from this thread(change text value by clicking drop down list) Where this problem was solved it did not work with my script so I'm going to go more in depth.
HTML
<li><input type="text" id="location"></li>
<div id="locationselect"></div>
User starts typing in their location into text input id="location", AJAX is used to return a list of locations that start with user input. (eg. "Lon" would return London, Long Eaton etc and returns results to as an unordered list)
getlocations.php
<?php
if ($location == '') {echo "";}
else {
echo "<ul>";
while($location = mysql_fetch_assoc($result)){
echo "<li>". $location['location'] ."</li>";
}
echo "</ul>";
}
?>
THIS ALL WORKS GREAT!!! I get the dropdown of the locations as user input is typed, so the AJAX part is working.
The problem I am having now is that ... It brings up a list of the locations as you type the letters HOWEVER
$('#locationselect li').click(function() {
$('#location').val($(this).text());
});
Does not seem to autocomplete the id="location" input text field when a list item is clicked. Is there something missing from the getlocations.php file?
Really Confused by this, apologies for a new thread but the last was technically answered =) Thanks for any help.
Upvotes: 0
Views: 540
Reputation: 1608
If I understand it correctly than you are binding the click event to any li under #locationselect before any are available. You should bind the click event after the li elements are loaded and rendered in the ajax call. Try this:
$('document').ready(function(){
$('#location').keyup(function() {
if ($('#location').length == 0) {
$('#locationselect').hide();
}
$('#locationselect').html("");
var location = $('#location').val();
location = $.trim(location);
$.ajax({
type:"post",
url:"getlocations.php",
data:"location="+location,
success:function(data){
$("#locationselect").html(data);
$('#locationselect li').click(function() {
$('#location').val($(this).text());
});
}
});
});
});
Upvotes: 1