Search code examples
javascriptgoogle-mapsgoogle-maps-api-3event-handling

How to retreive value on input autocomplete?


I would like to save entered value of input field to localStorage. I am trying to achieve this using input event which I listen on input element. It works fine when I input address manually or paste something in the input, but not when I click on google maps' autocomplete suggestion. For some reason input event is not being triggered by autocomplete action.

This is my input:

<input
  type="text"
  name="input"
  id="input"
  value=""
  placeholder="Enter destination"
  class="large pac-target-input"
  autocomplete="off"
>

This is how I save user's input to localStorage:

document.addEventListener('DOMContentLoaded', function() {
    const input = document.querySelector('[name="input"].large');
    if (input) {
        input.value = localStorage.getItem("movingto") || "";
        input.addEventListener('input', function() {
            localStorage.setItem("movingto", this.value);
        });
    }
});

const input = document.getElementById("input");
const autocomplete = new google.maps.places.Autocomplete(input, {
    // ... options
});

Full fiddle: https://jsfiddle.net/Sacred13/umwe9301/2/


Solution

  • I'm not an expert in maps API, but it seems that the autocomplete doesn't actually trigger input event on the input, so you could add another listener for when the autcomplete is actually triggered by adding place_changed event to the autocomplete instance.

    Basically just add this code at the bottom:

    autocomplete2.addListener("place_changed", () => {
      let input2 = document.querySelector('[name="input6"].large');
      if (input2) {
        localStorage.setItem("movingto", input2.value);
      }
    });
    

    here's the fiddle fork: https://jsfiddle.net/26zyfpqk/