I need to display that in the separate div (so .ui-autocomplete-loading
is not applicable here). I can start to show that when search
event is happened. But how can I understand when it should be hidden?
How to display loading icon when autocomplete search is performed?
Asked Answered
I'm assuming you're using a remote data source. If so, use $.ajax
inside of a function you supply to the source
parameter. For example:
$("#auto").autocomplete({
source: function(request, response) {
$("#loading").show(); // Where #loading is the loading indicator
$.ajax({
url: "Your_URL_HERE",
data: request.term,
success: function(data) {
response(data);
$("#loading").hide();
},
error: function() {
$("#loading").hide();
}
});
}
});
Working Example: http://jsfiddle.net/gKFJU/
@billynoah this is because of race condition. For example: user types "foo" which fires an XHR with term = "foo", then types "bar" which fires another XHR with term = "foobar". Suppose the "foo" request completes first; which means you hide the loading icon. But the menu will not display because autocomplete waits for the "foobar" request to complete in order to show the menu. Note that the plugin handles race conditions behind the scenes and intelligently handles out-of-order AJAX requests. –
Irade
ok thanks. i guess in that case using
open
and close
events is a better at removing the loading element only when the plugin has completed all current requests. Do you agree? Can you think of any better way to handle this? –
Stonedeaf @billynoah: Salman is right, this answer isn't really deep enough to handle race conditions with AJAX requests. What I'd do is look at the default implementation for the
source
function in the autocomplete widget and emulate that. Using open
and close
sounds like a good idea too. –
Shipyard CSS Solution
If the loading element is a sibling of the input control then CSS general sibling selector can be used:
.loading {
/* whatever */
}
#autocomplete.ui-autocomplete-loading ~ .loading {
background-image: url(loading.gif);
}
jQuery Solution
You can add the search
and response
event handlers.
$("#autocomplete").autocomplete({
delay: 500,
minLength: 3,
source: "/search.json",
search: function () {
$("#loading2").show();
},
response: function () {
$("#loading2").hide();
}
});
Note that this approach suffers from race conditions since (i) AJAX requests do not necessarily finish in the order they were started (ii) autocomplete may fire fewer response events than search.
© 2022 - 2024 — McMap. All rights reserved.
complete
event but no improvement. The only thing I've done that works is hide it on bothopen
andclose
autocomplete events. Any idea why this would be the case? The behavior seems to indicate there is sometimes a delay for the menu to update after the ajax completes. – Stonedeaf