One way to do it would be to trap both the keyup
event of the input and the click
event of the button (or submit
event of the form, if you have one) and test for a match on your datasource:
$(document).ready(function() {
var data = [
{label: 'Stack Overflow', value: 'http://stackoverflow.com'},
{label: 'Yahoo', value: 'http://yahoo.com'},
{label: 'Google', value: 'http://google.com'},
{label: 'Bing', value: 'http://bing.com'}
],
autoNav = function (e) {
var val = $("input#autocomplete").val().toLowerCase(),
url = '';
data.forEach(function (value, index, array) {
if (value.label.toLowerCase() === val) {
url = value.value;
}
});
if (url.length) {
window.location.href = url;
}
};
$("input#autocomplete").autocomplete({
"source": data,
"focus": function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
"select": function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
}).on('keyup', autoNav);
$('button[type="submit"]').on('click', autoNav);
});
Fiddle: http://jsfiddle.net/EpuL2/