Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery UI Autocomplete: Tabbing before results available.
var ingredients = [
{ID:"9", value:"Cocoa Powder"},
{ID:"11", value:"Baking Powder"}
];
$(".ingredient-label")
.autocomplete({
source: ingredients,
autoFocus: true,
select: function (e, ui) {
// Set the value of the hidden field.
$(e.target).parent().find('.ingredient-id').val(ui.item.ID);
},
change: function (e, ui) {
var $this = $(e.target),
val;
// If an item was selected.
if (ui.item) {
val = ui.item.ID;
} else {
// Grep searches the array using a custom function.
val = $.grep(ingredients, function (n, i) {
return (n.value === $this.val());
});
// If match found, assign it.
if (val.length) {
val = val[0].ID;
// If not assign the default.
} else {
val = 0;
}
}
// Assign the value to the hidden field.
$this.parent().find('.ingredient-id').val(val);
}
})
.on('blur', function () {
// On tab out trigger the select/change functions.
$(this).trigger('autocompleteselect').trigger('autocompletechange');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment