Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google place autocomplete by classname not working

Hi i have a textbox and on focus it autocomplete place,street, name this work for me if i select by id , but later i have many dynamic textbox control so for that i have fixed classname, same code not working if i select by classname

JS FIDDLE DEMO

Code:

 getPlace();
 getPlace_dynamic();

     function getPlace() {
         var defaultBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng(-33.8902, 151.1759),
         new google.maps.LatLng(-33.8474, 151.2631));
         var input = document.getElementById('Destination');
         // var input = document.getElementsByClassName('destination');
         var options = {
             bounds: defaultBounds,
             types: ['establishment']
         };
         autocomplete = new google.maps.places.Autocomplete(input, options);
     }

     function getPlace_dynamic() {
         var defaultBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng(-33.8902, 151.1759),
         new google.maps.LatLng(-33.8474, 151.2631));

         var input = document.getElementsByClassName('myClass');
         var options = {
             bounds: defaultBounds,
             types: ['establishment']
         };
         autocomplete = new google.maps.places.Autocomplete(input, options);
     }

<input id="Destination" tabindex="1" class="txt_box" type="text" />
</br>
</br>Later Dynamically generated
<input tabindex="1" class="myClass" type="text" />
<input tabindex="1" class="myClass" type="text" />
like image 646
Satinder singh Avatar asked Dec 15 '22 00:12

Satinder singh


1 Answers

document.getElementsByClassName('myClass')

returns an array of elements with that className(myClass).

So what you need to do is to iterate each element and assign it to Google autocomplete api like below

for (i = 0; i < input.length; i++) {
        autocomplete = new google.maps.places.Autocomplete(input[i], options);
}

JSFiddle

like image 143
Praveen Avatar answered Dec 27 '22 06:12

Praveen