问题
I'm new to jQuery, and facing a problem while trying to implement autocomplete that returns images (made by a member of the Stack) but with the possibility of choosing various values (Multiple Values). But in my code, the user can only select only one value.
Here's the jsfiddle:
http://jsfiddle.net/Igaojsfiddle/85SAF/
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "http://api.stackoverflow.com/1.1/users",
data: {
filter: request.term,
pagesize: 10
},
jsonp: "jsonp",
dataType: "jsonp",
success: function(data) {
response($.map(data.users, function(el, index) {
return {
value: el.display_name,
avatar: "http://www.gravatar.com/avatar/" +
el.email_hash
};
}));
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
};
});
回答1:
The problem is that you're sending the complete text from the textbox as a filter (e.g. "Name1, a") instead of just the part after the comma (e.g. "a"). You're correctly making requests (as can be seen by looking at the Network tab in the developer toolbar of your browser of choice), but you're not sending the correct data as part of the query. It seems as though you have started with a copy of the code from http://jqueryui.com/autocomplete/#multiple, but you haven't used the extractLast method. If you change the data part of the json call from
data: {
filter: request.term,
pagesize: 10
},
to
data: {
filter: extractLast(request.term),
pagesize: 10
},
It should work. I have updated your jsfiddle (http://jsfiddle.net/85SAF/10/) with this and it seems to work fine.
Hope it helps!
来源:https://stackoverflow.com/questions/15279041/implement-jquery-autocomplete-with-multiple-values-and-images