I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.