Tristan Tristan - 5 months ago 65
jQuery Question

How to clear the input bound to the Google Places Autocomplete?

Here is my issue: I am using Google Places Autocomplete to gather information about places from the user.

On the event "place_changed", I save this information. However I want to give the user the possibility to add multiple places. So after this place has been save I want to clear the input.

However Google Autocomplete automatically replace the last entry in the input field. Anyway to get rid of that?

The details :

var inputId_div = $("#myinput");
var options = {
types: ['(cities)']
};
var autocomplete = new google.maps.places.Autocomplete(inputId_div[0], options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var places = autocomplete.getPlace();
save_place(places);

console.log(inputId_div.val()); // "Paris, France"
inputId_div.val("");
console.log(inputId_div.val()); // (an empty string)

setTimeout(function(){
console.log(inputId_div.val()); // "Paris, France" (It's back!)
inputId_div.val("");
console.log(inputId_div.val()); // (an empty string)
},1);

setTimeout(function(){
console.log(inputId_div.val()); // (an empty string)
},10);

}


You will tell me, well that looks fine, just clear it in the timeout.
BUT when I click away from the input (it loses the focus). The last entry comes back again!

Any idea to fix that?
I haven't found in the Google documentation a function such as

autocomplete.clear();


Thanks!

Answer

It appears that the autocomplete internally listens to the blur-event of the input, so lets give it something to listen for and clear the field after that:

inputId_div.blur();    
setTimeout(function(){
 inputId_div.val('')
 inputId_div.focus();},10);