简体   繁体   中英

How to use google address autocomplete in dynamically added input field

I'm having hard time to figure this out. In my code there's a button which add dynamically input fields which is good. But I want that field to have autocompleted google address. But my function doesn't work, coz i don't know where to put it in order to achieve those.

(function($) {
$(document).ready(function() {


var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID


var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append(
            '<div><input type="text" class="form-control" id="searchInput" placeholder="Start typing and find your place in google map"><a href="#" class="remove_field">Remove</a></div>'); //add input box
        // Autocomplete google address
        function initMap() {
            var input = document.getElementById('searchInput');
            var autocomplete = new google.maps.places.Autocomplete(input);

        }
        initMap();
    }

});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); x--;
})

})
})(jQuery);

One issue with the above code is that your DOM will have multiple elements with id="searchInput" . Ids should be unique.

Perhaps try:

var newInput = $('<div><input type="text" class="form-control" placeholder="Start typing and find your place in google map"><a href="#" class="remove_field">Remove</a></div>');

$(wrapper).append(newInput);

new google.maps.places.Autocomplete(newInput.find("input"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM