Here is my attempt at making appendTo
work alongside jQuery autocomplete using an AJAX source.
I have several questions that may benefit others who are struggling to grasp the correct approach for implementing autocomplete with an AJAX source.
1) What exactly does
source: function(request, response) {...}
do and why is it necessary?
2) In what format does
function(data){ response($.map (data, function(obj) {
return the data? I understand it's in JSON format, but what is the purpose of .map
? Is it essential to include this step? Are there advantages?
3a) When utilizing appendTo
and renderItem
, is it mandatory to have the aforementioned success
data returned?
3b) Whether or not the above data is required, how can you properly utilize appendTo and renderItem to modify the formatting and presentation of your fetched 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 may seem like a lot to unpack, but I believe it will be a valuable resource for many JavaScript beginners, including myself.