I'm using a Google Places Autocomplete and I simply want it to select the top item in the results list when the enter key is pressed in the form field and suggestions exist. I know this has been asked before:
Google maps Places API V3 autocomplete - select first option on enter
Google maps Places API V3 autocomplete - select first option on enter (and have it stay that way)
But the answers in those questions don't seem to actually work, or they address specific added functionality.
It also seems like something like the following should work (but it doesn't):
$("input#autocomplete").keydown(function(e) {
if (e.which == 13) {
//if there are suggestions...
if ($(".pac-container .pac-item").length) {
//click on the first item in the list or simulate a down arrow key event
//it does get this far, but I can't find a way to actually select the item
$(".pac-container .pac-item:first").click();
} else {
//there are no suggestions
}
}
});
Any suggestions would be greatly appreciated!
I've read the many answers of this question, and of the linked questions' answers so many times, before finding that the best answer is this one (Nota: sadly, it's not the accepted answer!).
I've modified 2 or 3 lines to turn it into a ready-to-use function that you can copy/paste in your code and apply to many input
elements if needed. Here it is:
var selectFirstOnEnter = function(input) { // store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) { // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, and then trigger the original listener.
if (type == "keydown") {
var orig_listener = listener;
listener = function(event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which == 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {keyCode: 40, which: 40});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]); // add the modified listener
}
if (input.addEventListener) {
input.addEventListener = addEventListenerWrapper;
} else if (input.attachEvent) {
input.attachEvent = addEventListenerWrapper;
}
}
Usage:
selectFirstOnEnter(input1);
selectFirstOnEnter(input2);
...