【问题标题】:How to use google address autocomplete in dynamically added input field如何在动态添加的输入字段中使用谷歌地址自动完成
【发布时间】:2019-11-19 03:30:07
【问题描述】:

我很难弄清楚这一点。在我的代码中,有一个按钮可以动态添加输入字段,这很好。但我希望该字段具有自动完成的谷歌地址。但是我的功能不起作用,因为我不知道在哪里可以实现这些功能。

(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);

【问题讨论】:

    标签: javascript jquery html wordpress google-maps


    【解决方案1】:

    上述代码的一个问题是您的 DOM 将包含多个带有 id="searchInput" 的元素。 ID 应该是唯一的。

    或许可以试试:

    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"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 2021-06-15
      • 2017-08-04
      • 2023-03-04
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多