The correct event in google places autocomplete, select with the mouse

I use google autocomplete api as in docs and it works well. However, I have a form submitted with ajax every time it changes. It works fine, but when I use autocomplete for a location with the mouse (one-click location selection). It launches onchange and submits the form before the location is set.

How can I block this behavior? I mean send after a mouse click on autocomplete.

Here is a fiddle with an example: http://jsfiddle.net/8GnZB/2/

$(document).ready(function () { $location_input = $("#location"); var options = { types: ['(cities)'], componentRestrictions: { country: 'be' } }; autocomplete = new google.maps.places.Autocomplete($location_input.get(0), options); $("#search_form input").change(function () { var data = $("#search_form").serialize(); /* Serialize form & send it to the search view */ show_submit_data(data); return false; }); }); function show_submit_data(data) { $("#result").html(data); } <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=true"></script> <form id="search_form" action="" method="post" >location : <input id="location" name="location" type="text" /> <br/>data: <input id="data" name="data" type="text" /> </form>Sent data : <div id="result"></div> 

The only work I managed to work on was the timeout of the change() event, but rather ugly.

+7
source share
1 answer

To solve your problem, you need to bind the correct event for input, remember that the library has its own events.

The object you use to autocomplete

 autocomplete = new google.maps.places.Autocomplete($location_input.get(0), options); 

Now you can bind the place_changed event that it fires when you need it, at this point you can control everything you need.

 google.maps.event.addListener(autocomplete, 'place_changed', function() { var data = $("#search_form").serialize(); console.log('blah') show_submit_data(data); }); 

Here is a live example http://jsfiddle.net/8GnZB/7/

+27
source

All Articles