質問

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!

役に立ちましたか?

解決

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;
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top