Google maps autocomplete on clone elements

675 Views Asked by At

I have got this code to clone my input field when someone click on the add more button.

javascript

$(".multipleunitaddress").each(function(){
  var multipleunitaddressinput = $(this).get(0);
  autocomplete2 = new google.maps.places.Autocomplete(multipleunitaddressinput, 
  {
    componentRestrictions: {country: "nz"}
  });
});


$("#addmore").click(function(){
  var newelement = $("#multipleunitaddress").clone();
  $(this).before(newelement);
  autocomplete3 = new google.maps.places.Autocomplete(newelement,                                                      
  {
    componentRestrictions: {country: "nz"}
  });
})

html

<div class="controls" id="multipleunitaddresswrapper">
  <input type="text" id="multipleunitaddress" class="multipleunitaddress" name="multipleunitaddress" value="" class="required" placeholder="Property's Google-safe address" autocomplete="off">

  <button id="addmore" class="btn btn-danger">Add more</button>
</div>

The default input run google maps autocomplete fine. The add more button clones my inputs. However, for the new clone inputs, google maps autocomplete do not apply. How can I make Google maps autocomplete works on the clone element?

1

There are 1 best solutions below

0
On

I got it working using livequery with the following code

html

  <div class="controls">
    <div class="multipleunitaddresswrapper">
      <input type="text" class="multipleunitaddress" name="multipleunitaddress" value="" class="required" autocomplete="off">
    </div>
    <button id="addmore" class="btn btn-danger" type="button">Add more</button>
  </div>

javascript

$(".multipleunitaddress").livequery(function()
  {
    var multipleunitaddressinput = $(this).get(0);
    autocompleteInput = new google.maps.places.Autocomplete(multipleunitaddressinput, 
   {
    componentRestrictions: {country: "nz"}
  });
});

$("#addmore").click(function(){
  var newelement = $(this).prev(".multipleunitaddresswrapper").clone();
  newelement.find("input").val("");
  $(this).before(newelement);
})