Reputation: 614
I'm trying to achieve the following behavior.
When using Google Maps API's autocomplete, clicking with the mouse on an element in the list or pressing enter will select the desired element and fill in the input with necessary values. However, if you press enter while focus is still in the input element itself, nothing happens, so it's necessary to somehow solve that.
I have decided to solve that problem by selecting the first item from the autocomplete list:
$("#autocomplete").keypress(function(e){
if(e.which == 13) {
select-first-item();
}
});
It works well, but the problem is that it will select the first item even if you use the down arrow on the keyboard, browse the autocomplete list and then press enter while e. g. 4th result is selected.
How to solve this? I have tried with :focus
, but it doesn't seem very reliable. Sometimes it selected the first result, sometimes it selected the focused item from the list.
Google Maps adds class pac-item-selected
to the item selected in the list, so my last try was based on checking for length
.
$("#autocomplete").keypress(function(e){
if ( $( ".pac-item-selected" ).length ) {
if(e.which == 13) {
select-first-item();
}
}
}
However, as soon as you press anything, the class goes away and checking for length doesn't work. If I use event.preventDefault, the whole functionalitiy doesn't work, since autocomplete is obviously based on keypress/keydown/... events.
I couldn't make Maps work in my fiddle properly, so I have adapted an old fiddle: http://jsfiddle.net/pbbhH/1222/
Is there any solution for this?
Upvotes: 3
Views: 4079
Reputation: 3535
In addition to @dhara-paramar solution:
Just wanted to add new shorter version according to Google Maps Api Documantation:
var input_source = document.getElementById('input_source');
var autocomplete = new google.maps.places.Autocomplete(input_source);
autocomplete.addListener('place_changed', fillInAddress);
function fillInAddress() {
//your process here
};
Upvotes: 0
Reputation: 8101
using place_changed event of autocomplete you can check place has been changed:
var input_source = document.getElementById('input_source');
var autocomplete = new google.maps.places.Autocomplete(input_source);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// process
});
Upvotes: 3