Reputation: 12857
I am trying to make an autocomplete suggestion for countries listed in my database. I managed to get the list and I am trying to bind click event for entries for each country. Although I believe this is the way to do it, code is always using the last item's value and placing it to the input field.
Suggestions
is my autocomplete container and the text field that I want to update is the box
.
$('#box').on('input', function (){
var typedLocation = { 'location' : $(this).val() };
var key;
$.post( "/suggestions.php", typedLocation, function( data ) {
$('#Suggestions').html('').show();
for (key in data) {
$('#Suggestions').append('<div id="suggest' + key + '" >' + data[key] + '</div>');
$('#Suggestions').find('#suggest' + key).click(function (){
$('#Suggestions').hide();
$('#box').val(data[key]);
});
}
});
});
Upvotes: 0
Views: 92
Reputation: 12857
Instead of using the variable for setting the value of input field, I have used $(this).html()
in the click function.
Adopting it to Joe's example (as it seems more elegant):
var $elem = $('<div>' + data[key] + '</div>');
$elem.click(function () {
$('#Suggestions').hide();
$('#box').val($(this).html());
});
$('#Suggestions').append($elem);
Upvotes: 1