Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  98] [ 5]  / answers: 1 / hits: 17865  / 12 Years ago, thu, july 5, 2012, 12:00:00

My full code is here: http://jsfiddle.net/HfNk9/13/



I am looking to this example jqueryUi autocomplete - custom data and display.



Let's suppose the object projects is different and it looks like this:



project = [
{
name: 'bar',
value: 'foo',
imgage: 'img.png'
}
]


If I set source = project the autocomplete refers to project.value and not project.name.

How should I change this behaviour?






var autocomplete = function(element, data) {
var fixtures = [
{
avatar: http://www.placekitten.com/20/20,
name: 'aaaaaaaaa',
value: 'bbbbbbbbb'}
];

element.autocomplete({
minLength: 3,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), i);
response($.grep(fixtures, function(value) {
return matcher.test(value.name);
}));
},
create: function() {
console.log(fixtures)
element.val(fixtures.name);
},
focus: function(event, ui) {
element.val(ui.item.name);
return false;
},
select: function(event, ui) {
element.val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a><img src=' + item.avatar + ' />' + item.name + '<br></a>')
.appendTo(ul);
};
};

autocomplete($('#auto'));


My full code: http://jsfiddle.net/HfNk9/13/


More From » jquery

 Answers
22

You need to filter on a different property than the autocomplete widget searches on by default (as you've noticed it's name or value when using a source array with objects).



You can use a function instead of an array as the source and perform your own filtering that way:



element.autocomplete({
minLength: 3,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), i);
response($.grep(fixtures, function(value) {
return matcher.test(value.name);
}));
},
create: function() {
console.log(fixtures)
element.val(fixtures.name);
},
focus: function(event, ui) {
element.val(ui.item.name);
return false;
},
select: function(event, ui) {
element.val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a><img src=' + item.avatar + ' />' + item.name + '<br></a>')
.appendTo(ul);
};


Example: http://jsfiddle.net/QzJzW/


[#84439] Wednesday, July 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efrainjamiry

Total Points: 234
Total Questions: 110
Total Answers: 112

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;