Pregunta

Good day! I have a form that enables a user to dynamically add and remove input text fields. Each text field should suggest some values or autocomplete. Adding and removing fields are successful. However, only the first text field autosuggests.

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>

$(function() {
    var availableTags = @Html(Json.toJson(tagNames).toString); 

    var scntDiv = $('#addMore');
    var i = $('#addMore p').size() + 1;



    $('#addRT').live('click', function() {
            $('<p><label for="tags"><input id="tags" type="text" name="relatedTags.tag.name" placeholder="Name"/></label> <a href="#" id="remRT">Remove</a></p>', 
                    function() {
                        $( "#tags" ).autocomplete({
                            source: availableTags
                        });
                    }).appendTo(scntDiv);
            i++;

            return false;
    });

    $('#remRT').live('click', function() { 
            if( i > 1 ) {
                    $(this).parents('p').remove();
                    i--;
            }
            return false;
    });

});

$(function() {
    var availableTags = @Html(Json.toJson(tagNames).toString); 
    $( "#tags" ).autocomplete({
        source: availableTags
    });
});


</script>


But the same problem persists. Please help me figure this out. Thank you very much!

¿Fue útil?

Solución

Following my comments, this should solve at least your autocomplete function. The ID is dynamically created by using the iterator you already had in your code.

$('#addRT').live('click', function() {
        $('<p><label for="tags"><input id="tags'+i+'" type="text" name="relatedTags.tag.name" placeholder="Name"/></label> <a href="#" id="remRT">Remove</a></p>').appendTo(scntDiv);

        $( "#tags"+i ).autocomplete({
          source: availableTags
        });

        i++;

        return false;
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top