Google autocomplete input not working if not in focus











up vote
0
down vote

favorite












I have a webpage where I want to guide users into inputting an address by using Google Maps Autocomplete API.



I have 3 fields.
The first one is limited to suggesting only localities. configured as follows:



<input name="locality" type="text" class="form-control" id="locality" placeholder="Insert locality" required>


Then from javascript:



var input = document.getElementById('locality');
var autocomplete = new google.maps.places.Autocomplete(input, {
types : [ '(cities)' ]
});

autocomplete.setComponentRestrictions({'country': ['us']});

// Set the data fields to return when the user selects a place.
autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);

autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("Scegli tra i suggerimenti di Google o spostati nel campo successivo (Comune) per continuare con l'inserimento dei dati.");
return;
}

if (place.address_components) {
$("#locality").data('addresscomponents', place.address_components);

var locality = "";
if (getAddressPart(place.address_components, "locality") != undefined) {
locality = getAddressPart(place.address_components, "locality").long_name
if (getAddressPart(place.address_components, "locality").long_name != getAddressPart(place.address_components, "administrative_area_level_3").long_name) {
locality += ", " + getAddressPart(place.address_components, "administrative_area_level_3").long_name
}
} else {
locality = getAddressPart(place.address_components, "administrative_area_level_3").long_name
}

var region = getAddressPart(place.address_components, "administrative_area_level_2").short_name;
$("#locality").val(locality || "")

$("#inputAddressForGoogle").val($("#inputAddressForGoogle").val() + ", " + locality + ", " + region);
$("#inputAddressForGoogle").data("locality", locality);
$("#inputAddressForGoogle").data("region", region);

$("#inputRegion").val(getAddressPart(place.address_components, "administrative_area_level_2").long_name)
}
});

var getAddressPart = (addressComponents, type) => {
return addressComponents.find(el => {
return el.types.indexOf(type) >= 0
})
}


The second #inputRegion field of the three, used above, is only used to obtain and show to the user the region of the selected locality:



<input name="inputRegion" type="text" class="form-control" id="inputReagion" placeholder="Region" required>


The third input also used in the javascript code above, actually never gets focused



<input name="inputAddress" type="text" class="form-control" id="inputAddress" placeholder="" required
style="z-index: 99;background: transparent;">
<input name="inputAddressForGoogle" type="text" class="form-control" id="inputAddressForGoogle" placeholder="" required
style="color: #aaa;position: absolute;margin-top: -34px;z-index: -98;border: none;box-shadow: none;">


There's one input where the user is going to type, and one input underneath that is going to query Google's Autocomplete services with the value: User inserted address + locality + region.



JavaScript:



var input = document.getElementById('inputAddressForGoogle');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);
autocomplete.setTypes(['address']);

autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (place.address_components) {
$("#inputAddress").data('addresscomponents', place.address_components);

var street = getAddressPart(place.address_components, "route") ? getAddressPart(place.address_components, "route").short_name : ''
var streetNumber = getAddressPart(place.address_components, "street_number") ?
", " + getAddressPart(place.address_components, "street_number").short_name : ''

$("#inputAddress").val(street + streetNumber)
}
});


enter image description here



Now, while the user has in focus the third input, I want them to be able to move and select the Autocomplete's suggestions that are related to the input field underneath.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I have a webpage where I want to guide users into inputting an address by using Google Maps Autocomplete API.



    I have 3 fields.
    The first one is limited to suggesting only localities. configured as follows:



    <input name="locality" type="text" class="form-control" id="locality" placeholder="Insert locality" required>


    Then from javascript:



    var input = document.getElementById('locality');
    var autocomplete = new google.maps.places.Autocomplete(input, {
    types : [ '(cities)' ]
    });

    autocomplete.setComponentRestrictions({'country': ['us']});

    // Set the data fields to return when the user selects a place.
    autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);

    autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
    // User entered the name of a Place that was not suggested and
    // pressed the Enter key, or the Place Details request failed.
    window.alert("Scegli tra i suggerimenti di Google o spostati nel campo successivo (Comune) per continuare con l'inserimento dei dati.");
    return;
    }

    if (place.address_components) {
    $("#locality").data('addresscomponents', place.address_components);

    var locality = "";
    if (getAddressPart(place.address_components, "locality") != undefined) {
    locality = getAddressPart(place.address_components, "locality").long_name
    if (getAddressPart(place.address_components, "locality").long_name != getAddressPart(place.address_components, "administrative_area_level_3").long_name) {
    locality += ", " + getAddressPart(place.address_components, "administrative_area_level_3").long_name
    }
    } else {
    locality = getAddressPart(place.address_components, "administrative_area_level_3").long_name
    }

    var region = getAddressPart(place.address_components, "administrative_area_level_2").short_name;
    $("#locality").val(locality || "")

    $("#inputAddressForGoogle").val($("#inputAddressForGoogle").val() + ", " + locality + ", " + region);
    $("#inputAddressForGoogle").data("locality", locality);
    $("#inputAddressForGoogle").data("region", region);

    $("#inputRegion").val(getAddressPart(place.address_components, "administrative_area_level_2").long_name)
    }
    });

    var getAddressPart = (addressComponents, type) => {
    return addressComponents.find(el => {
    return el.types.indexOf(type) >= 0
    })
    }


    The second #inputRegion field of the three, used above, is only used to obtain and show to the user the region of the selected locality:



    <input name="inputRegion" type="text" class="form-control" id="inputReagion" placeholder="Region" required>


    The third input also used in the javascript code above, actually never gets focused



    <input name="inputAddress" type="text" class="form-control" id="inputAddress" placeholder="" required
    style="z-index: 99;background: transparent;">
    <input name="inputAddressForGoogle" type="text" class="form-control" id="inputAddressForGoogle" placeholder="" required
    style="color: #aaa;position: absolute;margin-top: -34px;z-index: -98;border: none;box-shadow: none;">


    There's one input where the user is going to type, and one input underneath that is going to query Google's Autocomplete services with the value: User inserted address + locality + region.



    JavaScript:



    var input = document.getElementById('inputAddressForGoogle');
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);
    autocomplete.setTypes(['address']);

    autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (place.address_components) {
    $("#inputAddress").data('addresscomponents', place.address_components);

    var street = getAddressPart(place.address_components, "route") ? getAddressPart(place.address_components, "route").short_name : ''
    var streetNumber = getAddressPart(place.address_components, "street_number") ?
    ", " + getAddressPart(place.address_components, "street_number").short_name : ''

    $("#inputAddress").val(street + streetNumber)
    }
    });


    enter image description here



    Now, while the user has in focus the third input, I want them to be able to move and select the Autocomplete's suggestions that are related to the input field underneath.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a webpage where I want to guide users into inputting an address by using Google Maps Autocomplete API.



      I have 3 fields.
      The first one is limited to suggesting only localities. configured as follows:



      <input name="locality" type="text" class="form-control" id="locality" placeholder="Insert locality" required>


      Then from javascript:



      var input = document.getElementById('locality');
      var autocomplete = new google.maps.places.Autocomplete(input, {
      types : [ '(cities)' ]
      });

      autocomplete.setComponentRestrictions({'country': ['us']});

      // Set the data fields to return when the user selects a place.
      autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);

      autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("Scegli tra i suggerimenti di Google o spostati nel campo successivo (Comune) per continuare con l'inserimento dei dati.");
      return;
      }

      if (place.address_components) {
      $("#locality").data('addresscomponents', place.address_components);

      var locality = "";
      if (getAddressPart(place.address_components, "locality") != undefined) {
      locality = getAddressPart(place.address_components, "locality").long_name
      if (getAddressPart(place.address_components, "locality").long_name != getAddressPart(place.address_components, "administrative_area_level_3").long_name) {
      locality += ", " + getAddressPart(place.address_components, "administrative_area_level_3").long_name
      }
      } else {
      locality = getAddressPart(place.address_components, "administrative_area_level_3").long_name
      }

      var region = getAddressPart(place.address_components, "administrative_area_level_2").short_name;
      $("#locality").val(locality || "")

      $("#inputAddressForGoogle").val($("#inputAddressForGoogle").val() + ", " + locality + ", " + region);
      $("#inputAddressForGoogle").data("locality", locality);
      $("#inputAddressForGoogle").data("region", region);

      $("#inputRegion").val(getAddressPart(place.address_components, "administrative_area_level_2").long_name)
      }
      });

      var getAddressPart = (addressComponents, type) => {
      return addressComponents.find(el => {
      return el.types.indexOf(type) >= 0
      })
      }


      The second #inputRegion field of the three, used above, is only used to obtain and show to the user the region of the selected locality:



      <input name="inputRegion" type="text" class="form-control" id="inputReagion" placeholder="Region" required>


      The third input also used in the javascript code above, actually never gets focused



      <input name="inputAddress" type="text" class="form-control" id="inputAddress" placeholder="" required
      style="z-index: 99;background: transparent;">
      <input name="inputAddressForGoogle" type="text" class="form-control" id="inputAddressForGoogle" placeholder="" required
      style="color: #aaa;position: absolute;margin-top: -34px;z-index: -98;border: none;box-shadow: none;">


      There's one input where the user is going to type, and one input underneath that is going to query Google's Autocomplete services with the value: User inserted address + locality + region.



      JavaScript:



      var input = document.getElementById('inputAddressForGoogle');
      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);
      autocomplete.setTypes(['address']);

      autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (place.address_components) {
      $("#inputAddress").data('addresscomponents', place.address_components);

      var street = getAddressPart(place.address_components, "route") ? getAddressPart(place.address_components, "route").short_name : ''
      var streetNumber = getAddressPart(place.address_components, "street_number") ?
      ", " + getAddressPart(place.address_components, "street_number").short_name : ''

      $("#inputAddress").val(street + streetNumber)
      }
      });


      enter image description here



      Now, while the user has in focus the third input, I want them to be able to move and select the Autocomplete's suggestions that are related to the input field underneath.










      share|improve this question













      I have a webpage where I want to guide users into inputting an address by using Google Maps Autocomplete API.



      I have 3 fields.
      The first one is limited to suggesting only localities. configured as follows:



      <input name="locality" type="text" class="form-control" id="locality" placeholder="Insert locality" required>


      Then from javascript:



      var input = document.getElementById('locality');
      var autocomplete = new google.maps.places.Autocomplete(input, {
      types : [ '(cities)' ]
      });

      autocomplete.setComponentRestrictions({'country': ['us']});

      // Set the data fields to return when the user selects a place.
      autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);

      autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("Scegli tra i suggerimenti di Google o spostati nel campo successivo (Comune) per continuare con l'inserimento dei dati.");
      return;
      }

      if (place.address_components) {
      $("#locality").data('addresscomponents', place.address_components);

      var locality = "";
      if (getAddressPart(place.address_components, "locality") != undefined) {
      locality = getAddressPart(place.address_components, "locality").long_name
      if (getAddressPart(place.address_components, "locality").long_name != getAddressPart(place.address_components, "administrative_area_level_3").long_name) {
      locality += ", " + getAddressPart(place.address_components, "administrative_area_level_3").long_name
      }
      } else {
      locality = getAddressPart(place.address_components, "administrative_area_level_3").long_name
      }

      var region = getAddressPart(place.address_components, "administrative_area_level_2").short_name;
      $("#locality").val(locality || "")

      $("#inputAddressForGoogle").val($("#inputAddressForGoogle").val() + ", " + locality + ", " + region);
      $("#inputAddressForGoogle").data("locality", locality);
      $("#inputAddressForGoogle").data("region", region);

      $("#inputRegion").val(getAddressPart(place.address_components, "administrative_area_level_2").long_name)
      }
      });

      var getAddressPart = (addressComponents, type) => {
      return addressComponents.find(el => {
      return el.types.indexOf(type) >= 0
      })
      }


      The second #inputRegion field of the three, used above, is only used to obtain and show to the user the region of the selected locality:



      <input name="inputRegion" type="text" class="form-control" id="inputReagion" placeholder="Region" required>


      The third input also used in the javascript code above, actually never gets focused



      <input name="inputAddress" type="text" class="form-control" id="inputAddress" placeholder="" required
      style="z-index: 99;background: transparent;">
      <input name="inputAddressForGoogle" type="text" class="form-control" id="inputAddressForGoogle" placeholder="" required
      style="color: #aaa;position: absolute;margin-top: -34px;z-index: -98;border: none;box-shadow: none;">


      There's one input where the user is going to type, and one input underneath that is going to query Google's Autocomplete services with the value: User inserted address + locality + region.



      JavaScript:



      var input = document.getElementById('inputAddressForGoogle');
      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);
      autocomplete.setTypes(['address']);

      autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (place.address_components) {
      $("#inputAddress").data('addresscomponents', place.address_components);

      var street = getAddressPart(place.address_components, "route") ? getAddressPart(place.address_components, "route").short_name : ''
      var streetNumber = getAddressPart(place.address_components, "street_number") ?
      ", " + getAddressPart(place.address_components, "street_number").short_name : ''

      $("#inputAddress").val(street + streetNumber)
      }
      });


      enter image description here



      Now, while the user has in focus the third input, I want them to be able to move and select the Autocomplete's suggestions that are related to the input field underneath.







      javascript google-maps google-maps-api-3






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 15:55









      500 Server error

      347716




      347716
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          It was enough to propagate all the keys to the underlying field.



          $("#inputAddress").on('keyup', (e) => {
          google.maps.event.trigger( document.getElementById("inputAddressForGoogle"), 'focus', {} );
          try {
          google.maps.event.trigger(document.getElementById("inputAddressForGoogle"), 'keydown', {keyCode: e.keyCode});
          } catch (e) {
          }
          });





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396834%2fgoogle-autocomplete-input-not-working-if-not-in-focus%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            It was enough to propagate all the keys to the underlying field.



            $("#inputAddress").on('keyup', (e) => {
            google.maps.event.trigger( document.getElementById("inputAddressForGoogle"), 'focus', {} );
            try {
            google.maps.event.trigger(document.getElementById("inputAddressForGoogle"), 'keydown', {keyCode: e.keyCode});
            } catch (e) {
            }
            });





            share|improve this answer

























              up vote
              0
              down vote



              accepted










              It was enough to propagate all the keys to the underlying field.



              $("#inputAddress").on('keyup', (e) => {
              google.maps.event.trigger( document.getElementById("inputAddressForGoogle"), 'focus', {} );
              try {
              google.maps.event.trigger(document.getElementById("inputAddressForGoogle"), 'keydown', {keyCode: e.keyCode});
              } catch (e) {
              }
              });





              share|improve this answer























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                It was enough to propagate all the keys to the underlying field.



                $("#inputAddress").on('keyup', (e) => {
                google.maps.event.trigger( document.getElementById("inputAddressForGoogle"), 'focus', {} );
                try {
                google.maps.event.trigger(document.getElementById("inputAddressForGoogle"), 'keydown', {keyCode: e.keyCode});
                } catch (e) {
                }
                });





                share|improve this answer












                It was enough to propagate all the keys to the underlying field.



                $("#inputAddress").on('keyup', (e) => {
                google.maps.event.trigger( document.getElementById("inputAddressForGoogle"), 'focus', {} );
                try {
                google.maps.event.trigger(document.getElementById("inputAddressForGoogle"), 'keydown', {keyCode: e.keyCode});
                } catch (e) {
                }
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 at 22:50









                500 Server error

                347716




                347716






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396834%2fgoogle-autocomplete-input-not-working-if-not-in-focus%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python