简体   繁体   English

如何将自动完成功能添加到动态创建的输入中?

[英]How to add autocomplete to dynamically created inputs?

sorry for asking a question that has been answered, I read them, but I could not figure out how to apply them to my problem. 很抱歉提出了一个已回答的问题,我已阅读它们,但无法弄清楚如何将其应用于我的问题。

Basically I have a form with this input 基本上我有这个输入的形式

<input class="auto" type="text" name="id_item[]" placeholder="Article ID" required style="width: 15%;"/>

and then I have an empty div under it, where I put newcly created inputs, when user click the add button 然后我有一个空的div,当用户单击添加按钮时,我将新创建的输入放在其中

<div id="next_items">
</div>

My function to create and delete new inputs looks like this 我创建和删除新输入的功能如下所示

$(document).ready( function() {
    $("#add_item").click( function() {
        $("#next_items").append('<input class="auto" class="new_id" type="text" name="id_item[]" placeholder="Article ID" required style="width: 15%;"/>');
    });

    $("#remove_item").click( function() {
        $(".new_id:last").remove();
    });
});  

and the last thing is my autocomplete js 最后一件事是我的自动填充js

$('input.auto').each(function() {
    $(this).autocomplete({
        source: "contract/auto",
        minLength: 1
    });
});

It works fine for my first input, which is there all the time, but when I tr to add new input with the button, it does not work. 对于我的第一个输入,它一直都很好,但我一直在用按钮添加新输入时,它不起作用。 I tried using the each function and it still does not work. 我尝试使用每个函数,但仍然无法正常工作。 Also the classes started to mix up in the created buttons. 同样,类也开始在创建的按钮中混合在一起。 How can I fix this problem? 我该如何解决这个问题?

You need to bind autocomplete for that textbox after appending it: 追加文本框后,需要为该文本框绑定自动完成功能:

$("#add_item").click( function() {
    $("#next_items").append('<input class="auto" class="new_id" type="text" name="id_item[]" placeholder="Article ID" required style="width: 15%;"/>');
    $("#next_items .auto:last").autocomplete({
        source: "contract/auto",
        minLength: 1
    });
});

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

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