Handle inject keypress event inside jQuery UI autocomplete
Is there a way to handle the event when the enter key is pressed in jquery's autocomplete function? If I click on the dropdown item I go to the next url
window.location.href = '/user?userId=' + ui.item.userId;
And it works great in the function selection section. But what if I need to change my url when I have typed a few letters and the dropdown results are shown, but I do not click on one of the items, instead I just press enter, how can I process it?
$('#search').autocomplete({
source: function(request, response) {
$.ajax({
url: "/search/users",
data: {
query: request.term
},
success: function(data) {
var transformed = $.map(data, function(el) {
return {
name: el.name,
email: el.email
};
});
response(transformed);
},
error: function() {
response([]);
}
});
},
select: function(event, ui) {
window.location.href = '/user?userId=' + ui.item.userId;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var $a = $("<a></a>").append(item.name);
highlightText(this.term, $a);
return $("<li></li>").append($a).appendTo(ul);
};
I tried with this but I am wondering if there is a better solution
$('#search').on('keypress', function(e) {
if (e.which == 13 && $(this).val()) {
window.location.href = '/users/list?name=' + $(this).val();
}
});
+3
source to share
1 answer