How to fire place_changed event for Google places auto-complete on Enter key

John Stephenson picture John Stephenson · Oct 10, 2012 · Viewed 58.3k times · Source

The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.

function locationAuto() {
        $('.search-location').focus(function () {
        autocomplete = new google.maps.places.Autocomplete(this);
        searchbox = this;

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var thisplace = autocomplete.getPlace();
            if (thisplace.geometry.location != null) {
                $.cookie.raw = true;
                $.cookie('location', searchbox.value, { expires: 1 });
                $.cookie('geo', thisplace.geometry.location, { expires: 1 });
            }
        });
});

The .search-location is a class on multiple textboxes. There is a submit button that takes the values from the cookies and redirects (server side)

Answer

Marcelo picture Marcelo · Oct 10, 2012

Adapted from Jonathan Caulfield's answer:

$('.search-location').keypress(function(e) {
  if (e.which == 13) {
    google.maps.event.trigger(autocomplete, 'place_changed');
    return false;
  }
});