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

时间:2016-12-23 18:06:13

标签: javascript jquery html autocomplete typeahead.js

我正在尝试使用Typeahead在动态创建的输入字段上运行自动完成功能。我有以下代码:

HTML:

<div class="input_fields_wrap">
     <a href="#" class="add_field_button">Add More Fields</a> </br>
     <div><input type="text" name="typeahead[]" class="typeahead tt-query" id="1"></div>    
     <div><input type="text" name="typeahead[]" class="typeahead tt-query" id="2"></div>
</div>

使用Javascript:

/***************Autocompletion***************/

                $(document).ready(function(){
                $('input.typeahead').typeahead({
                    name: 'typeahead',
                    remote:'search.php?key=%QUERY',
                    limit : 10
                    });
                });


/***************Create Input fields dynamically***************/

                    $(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 = 2; //initlal text box count

                        $(add_button).click(function(e)
                        {
                            if(x < max_fields)
                            {
                                x++; 
                                $(wrapper).append('<div><input type="text" name="typeahead[]" class="typeahead tt-query" id="' + x + '"><a href="#" class="remove_field">Remove</a></div>'); //add input box
                            }
                        });

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

我可以通过点击“添加更多字段”链接创建新的输入字段。 我的2个现有文本字段的自动完成功能为also working。 但是当我创建一个新的输入字段时,自动完成功能不起作用。 自动完成的数据来自MYSQL数据库。

我希望有人知道为什么这不起作用。

非常感谢你!

1 个答案:

答案 0 :(得分:0)

创建新元素时:

$(add_button).click(function(e)
{
    if(x < max_fields)
    {
        x++; 
        $(wrapper).append('<div><input type="text" name="typeahead[]" 
                   class="typeahead tt-query" id="' + x + '">
                   <a href="#" class="remove_field">Remove</a></div>'); //add input box
    }
});

您需要初始化相应的typeahead对象。在上一个 $(包装器).append 之后,您需要添加:

$('#' + x).typeahead({
      name: 'typeahead',
      remote:'search.php?key=%QUERY',
      limit : 10
});
相关问题