简体   繁体   English

在动态创建的输入字段上启用 jQuery 自动完成

[英]Enabling jQuery Autocomplete on dynamically created input fields

I've read almost every article i could find on how to accomplish this, but i'm still failing miserably.我已经阅读了几乎所有我能找到的关于如何实现这一点的文章,但我仍然失败得很惨。 mostly because i'm an amateur at jQuery\/Javascript.主要是因为我是 jQuery\/Javascript 的业余爱好者。

I have a website that contains one input element.我有一个包含一个输入元素的网站。 I've managed to get jQuery Autocomplete working nicely on this.我已经设法让 jQuery Autocomplete 在这方面工作得很好。 The problem is that when i dynamically add additional elements using the .append method, these new elements do not work with autocomplete.问题是当我使用 .append 方法动态添加其他元素时,这些新元素不适用于自动完成。

See jsfiddle: http:\/\/jsfiddle.net\/aktive\/r08m8vvy\/<\/a>见jsfiddle:http: \/\/jsfiddle.net\/aktive\/r08m8vvy\/<\/a>

see jsfiddle for full code sample

You must bind autocomplete after adding new elements添加新元素后必须绑定自动完成

$(wrapper).find('input[type=text]:last').autocomplete({
                source: availableAttributes
}); 

See example: http://jsfiddle.net/r08m8vvy/4/参见示例: http : //jsfiddle.net/r08m8vvy/4/

See http://jsfiddle.net/r08m8vvy/2/http://jsfiddle.net/r08m8vvy/2/

Give the new input an ID and call autocomplete on it.为新输入提供一个 ID 并对其调用自动完成。 The initial autocompate call you make won't include the dynamically added inputs.您进行的初始自动匹配调用将不包括动态添加的输入。

 $(wrapper).append('<div><input id="' + x + '" type="text" name="mytext"/><a href="#" class="remove_field">Remove</a></div>'); //add input box

 $( "input[id="+ x +"]" ).autocomplete({
     source: availableAttributes
 });    

I actually found that a more reliable way was to bind using 'on' with the 'focus' action to init the auto complete based on the field class and destory it on exit.我实际上发现一种更可靠的方法是使用“on”和“focus”动作进行绑定,以根据字段类初始化自动完成并在退出时销毁它。 This way it cleans up the garbage and only inits it once you need to.这样它就可以清理垃圾,并且只在您需要时才将其初始化。

I was using it with cloning rows though and even doing deep cloning, which would clone the plus and minus buttons for the rows, it wasn't cloning the autocomplete.我将它与克隆行一起使用,甚至进行深度克隆,这将克隆行的加号和减号按钮,它不是克隆自动完成。

var auto_opts = {...opts...}

$('body').on('focus', '.search_field', function(){
    $(this).autocomplete(auto_opts).on('blur', function(){$(this).autocomplete('destroy')});
    });

It also means that you aren't forced into using the last row because it works on the field as you focus on it这也意味着您不会被迫使用最后一行,因为它在您专注于该领域时适用

I Updated the fiddle http://jsfiddle.net/r08m8vvy/5/我更新了小提琴http://jsfiddle.net/r08m8vvy/5/

You have to bind the autocomplete for new element您必须为新元素绑定自动完成功能

$(wrapper).append($('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>').find(":text").autocomplete({
    source: availableAttributes
}));

Here is the simpler way to use autocomplete for dynamically created input fields.这是对动态创建的输入字段使用自动完成的更简单方法。

$('body').on('focus', '.dynamic-input-class', function (e) {
 $(this).autocomplete({
  minLength: 2,
  delay: 500,
  source: function (request, response) {
   $.ajax( {
      url: "server side path that returns json data",
      data: { searchText: request.term},
      type: "POST",
      dataType: "json",
      success: function( data ) {
        $("#data-success").html(data.returnedData); //returnedData is json data return from server side response
      }
    });
  }
 });
});
<script>
    $(document).ready(function() {
        
        var nhlTeams = ['Atlanta', 'Boston', 'Buffalo', 'Calgary', 'Carolina', 'Chicago', 'Colorado', 'Columbus', 'Dallas', 'Detroit', 'Edmonton', 'Florida', 'Los Angeles', 'Minnesota', 'Montreal', 'Nashville', ];
        var nbaTeams = ['New Jersey', 'New Rork', 'New York', 'Ottawa', 'Philadelphia', 'Phoenix', 'Pittsburgh', 'Saint Louis', 'San Jose', 'Tampa Bay', 'Toronto Maple', 'Vancouver', 'Washington'];
        var nhl = $.map(nhlTeams, function (team) { return { value: team, data: { category: 'Section A' }}; });
        var nba = $.map(nbaTeams, function (team) { return { value: team, data: { category: 'Section B' } }; });
        var teams = nhl.concat(nba);

        // Initialize autocomplete with local lookup:
        $('body').on('focus', '.db_items', function(){
            $(this).autocomplete({
                lookup: teams,
                minChars: 1,
                onSelect: function (suggestion) {
                    $('#selection').html('You selected: ' + suggestion.value);
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results',
                groupBy: 'category'
            });
        });

    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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