How to tell when google places autocomplete suggestion was not used?

betaorbust picture betaorbust · Jan 11, 2013 · Viewed 8.3k times · Source

Short version:

I'm using google's autocomplete places from the Google Places Library (here https://developers.google.com/maps/documentation/javascript/places) and I need to tell when a user has selected a place from the auto-complete list and when they have clicked elsewhere, tabbed out, etc.

My goal is to run a function when a user interacts with the input element but does not select an autocomplete option.

More details:

In looking at the documentation, it appears the only event is fired when (really, if) the places change, which happens after a (potentially long) server round trip. If the user doesn't select anything from the list, that event is never fired. (Docs at https://developers.google.com/maps/documentation/javascript/reference?hl=fr#Autocomplete)

I can attach a listener to the blur event for the input element the autocomplete attaches to, but the problem is that the blur event happens well before the places_changed event happens.

So far have tried a number of things including listening for events on the autocomplete suggestions with something like the following:

$('body').on('click', '.pac-item', function(){alert.log('yay!');});

the google library apparently eats the events though.

Any help would be greatly appreciated.

Thanks!

Answer

Robert Dodd picture Robert Dodd · Feb 3, 2013

Rather than using an event to check, you should check when the form submits. Here it is step by step:

  1. When user selects a place, store the place AND the text value of the input
  2. When the form submits, check if the value of the input is the same as what you saved
  3. If it is different, or if there is no place saved, then perform a manual places request

Demo: http://jsfiddle.net/robertdodd/FSRd8/7/

I put together a small demo above. What I did is attach a validation method to the form. This method will check the data before submitting the form, and if required perform a manual lookup first.

function validateForm() {
    searchfield = $('#searchfield').val();
    if (searchfield == "" || searchfield == null) { 
        // No text entered
    } else if (place && searchfield == placesearch) { 
        // Success
        return true;
    } else { 
        // place info and search text do not match, perform manual lookup   
        // when lookup is complete, the callback function will store the place info
        // and resubmit the form
    }
    return false;
}

This is just an outline of what happens, all the code is in the demo if you wish to see it.

I hope this helps you!