I managed to get jQuery UI autocomplete to work. However since I use it in many input fields I wanted to make it more generic so I don't have to replicate it. So instead of the following code:
$(function() {
var cache = {};
$("#searchGuyInput").autocomplete({
minLength: 2,
source: function(request, response) {
// Getting a JSON array to populate the list
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("c_select_guy.php", {request: term}, function(data, status, xhr) {
cache[ term ] = data;
response(data);
});
},
select: function(event, ui) {
// What happens once I have selected a name from the list
if (ui.item){
createInputField(ui.item.Name + " " + ui.item.Surname,ui.item.guyID);
}
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
// Here I can format the JSON array to display the rows in the list
return formatted;
};
function createInputField(message, guyID) {
// creates a new div for the selected element
};
});
I tried to use:
function autocomp(inputID) { //CHANGED
var cache = {};
$(inputID).autocomplete({ //CHANGED
minLength: 2,
source: function(request, response) {
// Getting a JSON array to populate the list
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("c_select_guy.php", {request: term}, function(data, status, xhr) {
cache[ term ] = data;
response(data);
});
},
select: function(event, ui) {
// What happens once I have selected a name from the list
if (ui.item){
createInputField(ui.item.Name + " " + ui.item.Surname,ui.item.guyID);
}
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
// Here I can format the JSON array to display the rows in the list
return formatted;
};
function createInputField(message, guyID) {
// creates a new div for the selected element
};
}
autocomp("#searchGuyInput"); //CHANGED
I highlighted the 3 changes with //CHANGED comments for you.
However now even though the autocomplete returns me a nice populated list of elements, when I select from the elements in the autocomplete the ui.item variable in the select function is undefined and it doesn't work anymore!
What am I understanding wrong?
I thought the $(function()); was just a way of defining an anonymous function in javascript and hence if I made it named I could call it multiple times for different input fields.