Reputation: 23
I've a conditional ajax function call. On receiving response, data is binded to the autocomplete. The problem is that, on entering first key, Autocomplete list doesn't shows up even though it has values binded to it. The list shows up only after entering the subsequent letter(s).
$("#AutoComplete").on('keyup', function (event)
{
if ($("#AutoComplete").val().length <= 5 )
{
GetData();
}
});
function GetData()
{
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: '{"key":"' + $("#AutoComplete").val() + '"}',
dataType: "json",
success: function (data)
{
var output= $.map(data, function (item)
{
return {
label: item.Name,
value: item.ID
};
});
$("#AutoComplete").autocomplete({
source: output,
autoFocus: true,
});
}
});
}
Upvotes: 0
Views: 145
Reputation: 30893
Consider the following example.
$("#AutoComplete").autocomplete({
source: function(req, resp) {
if (req.term.length <= 5) {
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: {
key: req.term
},
dataType: "json",
success: function(data) {
var output = $.map(data, function(item) {
return {
label: item.Name,
value: item.ID
};
});
resp(output);
}
});
}
},
autoFocus: true,
});
You can use a Function for the Source:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A
request
object, with a single term property, which refers to the value currently in the text input. For example, if the user enters"new yo"
in a city field, the Autocompleteterm
will equal"new yo"
.A
response
callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
https://api.jqueryui.com/autocomplete/#option-source
Upvotes: 1