When I try to implement auto-complete using the code below I get an error stating:
.data("autocomplete") is undefined
How ever if I remove the .data() method from the end it works fine (just with out the customizable graphics that .data() provides). Can anyone tell me what's going wrong?
$("input#testInput").bind("autocompleteselect", function (event, ui) {
}).autocomplete({
appendTo: "#autoCompList",
source: function (request, response) {
$.ajax({
url: JSONP CALL URL
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.data, function (item) {
fbPageJson = item;
return {
label: item.name,
image: item.picture,
json: item,
}
}));
},
});
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><img src='" + item.image + "' alt='no photo'/></a>" + item.label).appendTo(ul);
};
I had the same problem and based on the 1.10.0 version of jquery ui, I think you should try
data('uiAutocomplete')
instead of
data('autocomplete')
Based on Johnny's comment, I checked how the .data() function works. Yes, jQuery returns null from .data() call when selector does not find any items.
So if there is no matching element for your selector, then no autocomplete object is created and added to the custom data object.
So it seems it is better to do this:
$(selector).autocomplete({ your autocomplete config props here });
if ( $(selector).data() ) {
// some jQueryUI versions may use different keys for the object. so to make sure,
// put a breakpoint on the following line and add a watch for $(selector).data().
// then you can find out what key is used by your jQueryUI script.
var ac = $(selector).data('uiAutocomplete');
if ( ac ) {
// do what you want with the autoComplete object. below is the changed version of an example from jqueryUI autocomplete tutorial
ac._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
}
}