简体   繁体   中英

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 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

$('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
    });
});

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