I am using jQuery UI AutoComplete control (just upgraded to jQuery UI 1.8.1). Whenever the user leaves the text field, I want to set the contents of the text field to a known value and set the hidden identifier field for the selected value. In addition, I want the page to be sent back when the contents of the text field were changed.
I currently implement this when the autocomplete select event sets a hidden identifier, and then a change event in a text field that sets the value of the text field and, if necessary, returns the message back.
If the user just uses the keyboard, this works just fine. You can enter, use the up and down arrows to select a value, and then the tab to exit. The select event fires, the identifier is set, and then the change event occurs, and the page returns.
If the user starts to enter text, and then uses the mouse to select from the autocomplete options, but the change event is triggered (when does the focus go to the autocomplete menu?), And the page returns before the selection event has the opportunity to set the ID.
Is there a way to make the change event not fire until a selection case is selected, even if the mouse is used?
$(function() {
var txtAutoComp_cache = {};
var txtAutoComp_current = { label: $('#txtAutoComp').val(), id: $('#hiddenAutoComp_ID').val() };
$('#txtAutoComp').change(function() {
if (this.value == '') { txtAutoComp_current = null; }
if (txtAutoComp_current) {
this.value = txtAutoComp_current.label ? txtAutoComp_current.label : txtAutoComp_current;
$('#hiddenAutoComp_ID').val(txtAutoComp_current.id ? txtAutoComp_current.id : txtAutoComp_current);
} else {
this.value = '';
$('#hiddenAutoComp_ID').val('');
}
});
$('#txtAutoComp').autocomplete({
source: function(request, response) {
var jsonReq = '{ "prefixText": "' + request.term.replace('\\', '\\\\').replace('"', '\\"') + '", "count": 0 }';
if (txtAutoComp_cache.req == jsonReq && txtAutoComp_cache.content) {
response(txtAutoComp_cache.content);
return;
}
$.ajax({
url: 'ajaxLookup.asmx/CatLookup',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonReq,
type: 'POST',
success: function(data) {
txtAutoComp_cache.req = jsonReq;
txtAutoComp_cache.content = data.d;
response(data.d);
if (data.d && data.d[0]) { txtAutoComp_current = data.d[0]; }
}
});
},
select: function(event, ui) {
if (ui.item) { txtAutoComp_current = ui.item; }
$('#hiddenAutoComp_ID').val(ui.item ? ui.item.id : '');
}
});
});