26

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 inputDiv = $('#myinput');
var options = {
  types: ['(cities)']
};
var autocomplete = new google.maps.places.Autocomplete(inputDiv[0], options);

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var places = autocomplete.getPlace();
    savePlaces(places);

    console.log(inputDiv.val()); // 'Paris, France'
    inputDiv.val('');
    console.log(inputDiv.val()); // (an empty string)

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

    setTimeout(function() {
        console.log(inputDiv.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!

Tristan
  • 3,192
  • 3
  • 20
  • 32

7 Answers7

18

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);
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • 1
    Well it does work! Altough it's quite a hack =) The only problem is that it "flashes" the autocomplete dropdown during a fraction of a millisecond. – Tristan Jan 18 '13 at 09:38
  • 1
    Yes, I've seen that. But the only other option I found was to replace the input with a new input and create a new autocomplete, Im afraid this creates memory-leaks. You may try to set the visibility of the input to "hidden" at the begin and back to "visible" at the end. – Dr.Molle Jan 18 '13 at 10:04
  • Mm you can't focus on a hidden input though. – Tristan Jan 18 '13 at 10:51
  • Sorry, I don't mean the input, I mean the dropdown `$('.pac-container')` – Dr.Molle Jan 18 '13 at 10:55
  • I tried but Google doesn't let you hide it, it brings it back automatically! It's a pity they don't have a method to clear that cleanly without having to go though all this. – Tristan Jan 18 '13 at 11:12
  • The solution works for me. I cannot see anything "flashing". The dropdown disappears and input is ready to find a new place. +1 for this solution. – steven May 21 '13 at 05:38
  • Ah ok, it looks like flashing if you click with the mouse on the dropdown instead of using the enter-key. I use a timeout of 2000 now instead of 10. Think it looks better... – steven May 21 '13 at 05:45
  • Test on lastest firefox and Chrome version, you can use a timeout with 0 duration like: `code` inputId_div.blur(); setTimeout(function() { inputId_div.val(''); inputId_div.focus(); }, 0);`code` – heralight Jun 06 '13 at 21:35
  • This answer is excellent. Been knocking my head out for hours. Thanks. – Trevor McKendrick Dec 31 '13 at 01:52
13

to clear place you can use :

autocomplete.set('place',null);

it triggers place_change event too.

grogro
  • 525
  • 4
  • 8
11

The previous term persists in the autocomplete object.

Solution: Clear the input box then create a new autocomplete object. Also be sure to remove previous event listeners.

Declaration:

var input = document.getElementById('autocomplete');
var autocomplete;
var autocompleteListener;
var onPlaceChange = function() {...};

var initAutocomplete = function() {
  autocomplete = new google.maps.places.Autocomplete(input);
  autocompleteListener = google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChange);
};

To clear:

input.value = "";
google.maps.event.removeListener(autocompleteListener);
initAutocomplete();

The previous autocomplete object should be garbage collected. Please correct me if I'm wrong. To be sure you are exposing memory leaks, you can manually delete it.

Shu
  • 268
  • 3
  • 9
2

Not sure if this problem is still around but I found a fix that worked for me

google.maps.event.addListener(autoComplete, 'place_changed', function() {   
   $this.one("blur",function(){
      $this.val("");
   });

   //[DO YOUR CODE HERE]

   setTimeout(function(){
      $this.val(""); 
   },10); 
});

$this is a jQ reference to the autocomplete field. The blur event will trigger when you type in your value and tab into the autocomplete list and hit enter. When you click somewhere with the mouse, the blur event will trigger and clear the field.

If you use mouse directly after typing to select result, the blur is not triggered. Then the timeout will remove the value from your field.

It seems like a ridicolous hack to clear the field after input but I spent 4 hours searching the net and looking though the api of google and couldnt find a better solution.

Mattijs
  • 3,265
  • 3
  • 38
  • 35
0
import React, { useRef } from 'react';
import { Autocomplete } from '@react-google-maps/api';

const MyComponent = () => {
const autoCompleteInputRef = useRef();

const clearAutoCompleteInput = () => {
  const allInputs = 
    autoCompleteInputRef.current.querySelectorAll('input');
  allInputs.forEach(singleInput => singleInput.value = '');
}

return (
  <Autocomplete>
    <TextField
     label="Place to see"
     ref={autoCompleteInputRef}
   />
 </Autocomplete>
)
}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 17 '23 at 11:57
-1

As a slight enhancement to Dr.Molle's excellent answer you can use the z-index property to work around the flash, at least in recent browsers:

var input = $('#[id of autocomplete field]');
$(input).blur();
setTimeout(function() {
    var container = $('.pac-container');
    var zIndex = $(container).css('z-index');
    $(container).css('z-index', -1);
    input.val('')
    input.focus();
    setTimeout(function() {
        $(container).css('z-index', zIndex);
    }, 200);
}, 10);
-4

Try:

document.getElementById('myinput').value = '';

or

inputId_div.value = '';

I am not sure why you're using inputId_div[0]. I guess it must be a jQuery thing.

Marcelo
  • 9,387
  • 3
  • 35
  • 40
  • Yes I use inputId_div[0] just because I prefer using jQuery in general. – Tristan Jan 17 '13 at 17:06
  • @Tristan, right but what is the variable pointing to the input field? inputId_div[0] would suggest that inputId_div is an array, where it should be a scalar. (I never used jQuery). – Marcelo Jan 17 '13 at 17:24
  • inputId_div[0] in jQuery's var inputId_div = $("#myinput"); is the equivalent of inputId_div in JavaScript's var inputId_div = document.getElementById(inputId); – Tristan Jan 17 '13 at 17:30