Home > Software engineering >  How to retreive value on input autocomplete?
How to retreive value on input autocomplete?

Time:12-28

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"
  
  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/

CodePudding user response:

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/

CodePudding user response:

According to google maps documentation there is a place_changed event which you should use instead of native input event you are using.

So this would look like this in your case:

autocomplete.addListener("place_changed", () => {
    const place = autocomplete.getPlace();
    console.log({ place });
    // It will log "place" object which contains all useful info you can use (including full address).
})
  • Related