I am feeding a jQuery UI autocomplete off of a local array like so:
var articleCategories = [
{
label: "Technical",
value: 1
},
...
];
I'd like the control to be able to display only the labels in the suggestion box, which it does, and also only to display the label of the selected item in the target input field, which in my case is a textbox with the id as txtCategory.
function displaySelectedCategoryLabel(event, ui) {
$("#txtCategory").val(ui.item.label);
$("#hidSelectedCategoryId").val(ui.item.value);
};
var autoComplete = $("#txtCategory").autocomplete({
source: articleCategories,
classes: ...,
position: ...,
focus: function (event, ui) {
$("#txtCategory").val(ui.item.label);
},
select: function (event, ui) {
displaySelectedCategoryLabel(event, ui);
},
change: function (event, ui) {
displaySelectedCategoryLabel(event, ui);
}
});
So, I provided overrides for all the three, the focus, select and change events. When I step through in the debugger, I see them all behave just as I expect, except for one small aberration, as described below.
Here is what happens:
When I change focus by hovering my mouse over the items in the suggestion box, the
focusevent works just fine, displaying the labels in the target input field.However, if I navigate the items in the suggestion box using my keyboard keys, once again, only the
values appear in the target input field. Do I need to overide thekeypress,keyupandkeydownevents also? But of which control, since the suggestion box is dynamically created.When I select an entry from the suggestion box, the target input field displays the
labelobeying my handler, but only briefly, like described above. It soon changes back to displaying thevaluefor as long as I stay inside the target control.And as expected, as soon as I remove focus from the target control to outside, the change event occurs and the target input field starts displaying the
labelas per my handler.
What's going on? Am I missing an event handler?
Demo
Here is a working demo that illustrates the problem. Please download the entire folder named TestJQueryUIAutoComplete as it has the jQueryUI javascript files and the CSS files. In case you already have these CSS and JS files, then you only need to download the TestJQueryUIAutoComplete.html file.