Reputation: 1
I am currently working on a Spring mvc project in which I am using the jQuery autocomplete plugin to load data from a JSON file rendered from the server.
$('#searchTerm').autocomplete({
serviceUrl: '${ctx}/search/searchAutocomplete',
paramName: "parameterName",
delimiter: ",",
transformResult: function(response) {
return {
suggestions: $.map($.parseJSON(response), function(item) {
return {
value: item.userName + " , " + item.userId + ", " +
item.pathToImageFile , data: item
};
})
};
},
onSelect: function (suggestion) {
$(this).val(suggestion.data.userName);
console.log(suggestion.data.userId);
console.log(suggestion.data.pathToImageFile);
window.location.href = "${ctx}/userPage?
userID="+suggestion.data.userId;
}
});
This code works as expected. I am able to show the data of the suggestions in the suggestions list, and I am able to redirect to another page when selecting the item.
My inquiry is, how do I use the data from item.pathToImageFile to generate an image of a profile picture whithin the suggestions list? Similar to how facebook shows the profile pictures of users or groups when you search.
I went over the following similar topics here:
jQuery UI - Formatting the autocomplete results. Add image possible?
Jquery UI autocomplete - images IN the results overlay, not outside like the demo
How to change rendering of dropdown in jquery ui autocomplete attached to a class?
However I can't seem to apply the accepted answers in my code. In plain html and javascript, I know the syntax for each suggestion item should look something like this:
'<img src="'+ suggestion.data.pathToImageFile + '"/>'
'<p>' +suggestion.data.userName + '</p>'
I just can't seem to figure out the configurations and built in methods of the autocomplete plugin. The documentation does not help at all. Hope someone can help me out. Thanks
Upvotes: 0
Views: 1124
Reputation: 1806
You need to add .data("ui-autocomplete")._renderItem = function (ul, item) {
in my AJAX response the item.label already contains the needed HTML code with the correct format (I don't use images, but other formatting)
$('#searchTerm').autocomplete({
serviceUrl: '${ctx}/search/searchAutocomplete',
paramName: "parameterName",
delimiter: ","
/* This is the part to be implemennted */
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
You need to adjust the code and your AJAX response, but I think you can take it from here...
Upvotes: 1
Reputation: 964
I can't help with the jquery.autocomplete plugin, but if you can't get it to work the Select2 plugin features this functionality and it is well documented on their examples page on github here (look in the "Data Sources -> Loading remote data"
, section).
Perhaps you might get some insight/inspiration from there? Hope that's helpful!
Upvotes: 0