JQuery .autocomplete() Select Event Only Triggers When Widget Loses Focus
Solution 1:
I think your main issue is that you're trying to use _txtConvenzionato.val()
to get the selected value. The form element's value is updated after the select
event. Use the ui.item
from the event arguments to obtain the selected value.
A better approach (with a few more improvements):
// general-use "Ajax JSON POST" function, likely to be helpful in other places, too
$.postJSON = function (url, data, success) {
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: success || null
});
};
var Convenzionati = $.postJSON("/Service/WSDataService.asmx/GetConvenzionati", {})
.then(function (data) {
return data.d.split("<br />");
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
});
$(function () {
Convenzionati.done(function (items) {
$("input[id$='_txtConvenzionato']").autocomplete({
source: items,
select: function (event, ui) {
var _data = ui.item, _value;
// calculate _value ...
$("input[id$='_hdnConvenzionato']")
.val(_value)
.closest("form").submit();
}
});
});
});
Doing the $.postJSON
request before the $()
ensures that it starts loading as soon as possible, even before the rest of the page is ready - there is no need to wait for "document ready" to request the autocomplete items. We use the request's .then()
to transform the response (split at <br>
) for later use.
Inside the $()
we only react to the request's .done
, which will receive the already splitted items, and set up the autocomplete as soon as that's possible. This way your page initializing code and the autocomplete items can load in parallel.
Post a Comment for "JQuery .autocomplete() Select Event Only Triggers When Widget Loses Focus"