Good evening everyone. I'm trying to make a set of fields for entering cities with auto-completion. Found the following solution:

<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script> <script> function initialize() { var input = document.getElementById('searchTextField'); var options = { types: ['(regions)'], }; var autocomplete = new google.maps.places.Autocomplete(input, options); google.maps.event.addListener(autocomplete, 'place_changed', function() { var place = autocomplete.getPlace(); //получаем место console.log(place); console.log(place.name); //название места console.log(place.id); //уникальный идентификатор места }); } google.maps.event.addDomListener(window, 'load', initialize); </script> 

In html:

 <input id="searchTextField" size="50" type="text" /> 

But here it goes for a specific element with id, but it is necessary that it works for several inputs with a specific class. How to be in this case?

    2 answers 2

    unfortunately, and perhaps vice versa, not all browsers can use document.getElementsByClassName.

    It’s also not good to use one ID for several elements. therefore, a logical solution would be to reconsider the construction of the form. most likely you simply do not need as many input

    • This is all clear, thank you for the answer, but I still need several fields on the same page with autocomplete. Maybe someone else will offer something. I would be very grateful. - Mitriy

    Js code:

     function initAutocomplete () { var inputs = $('.searchTextField'); var options = { types: ['(regions)'], }; $(inputs).each(function (i, element) { var autocomplete = new google.maps.places.Autocomplete(element, options); google.maps.event.addListener(autocomplete, 'place_changed', function () { var place = autocomplete.getPlace(); //получаем место console.log(place); console.log(place.name); //название места console.log(place.id); //уникальный идентификатор места }); }); } 

    In html:

     <input class="searchTextField" size="50" type="text" />