Below is my attempt at getting appendTo
to work with jQuery autocomplete with AJAX source.
I have multiple questions, which will hopefully help many others who are struggling with understanding the correct way to implement autocomplete with and AJAX source.
1) source: function(request, response) {...}
What does this do? Why is it needed.
2) What format does function(data){ response($.map (data, function(obj) {
return the data in? I realize the data is in JSON format, but what is the point of .map
? Is it necessary to do this? Are there benefits?
3a) When using appendTo
and renderItem
, is it necessary to have the above mentioned success
data returned?
3b) Either or, depending on the above data, how do you correctly use appendTo and renderItem to change the formatting and display of your retrieved values?
$(function() {
$( ".find_group_ac" ).autocomplete({
minLength: 1,
source: function(request, response) {
$.ajax({
url: "welcome/search/",
data: { term: $(".find_group_ac").val()},
dataType: "json",
type: "POST",
success: function(data){ response($.map
(data, function(obj) {
return {
label: obj.name + ': ' + obj.description,
value: obj.name,
id: obj.name
};}));}
});
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
This might seem like a lot to answer, but I'm sure it will be valuable to many javascript newbies and certainly myself.