Jquery自动完成-字符串数组

jquery autocomplete - string array

本文关键字:字符串 数组 Jquery      更新时间:2023-09-26

我的web表单模型(AdtFormModel)有这个变量:

public List<String> TemoinsVille { get; set; }

我使用列表是因为我希望用户能够动态地在表单中添加更多的'TemoinsVille'。现在我有两个文本框,当我填充它们时,我的控制器接收到一个包含2个项目的字符串列表。稍后我会添加动态添加TemoinsVille的功能。

在我的表单中,我想为这个TemoinVille变量使用一个自动完成字段。我使用了一个叫做AutocompleteTous的方法,我在表单的其他地方使用了它。我不知道如何编写脚本,使自动完成为第二个TemoinVille输入工作。

我的JQuery代码是:
   var auto5 = $('#AdtFormModel_TemoinsVille').autocomplete({
        source: '@Url.Action("AutocompleteTous", "InvForm")',
        minLength: 3,
        delay: 400
    }).data("ui-autocomplete");
    auto5._renderItem = function (ul, item) {
        return $("<li>")
            .attr("ui-autocomplete-item", item)
            .append(item.label.split("|")[0])
            .appendTo(ul);
    };
    auto5._renderMenu = function (ul, items) {
        var that = this;
        $.each(items, function (index, item) {
            that._renderItemData(ul, item);
        });
        $(ul).addClass("dropdown-menu");
    };

在我看来,我有一个TemoinVille文本框输入:

@Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) @Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { @class = "text-danger" })
@Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) @Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { @class = "text-danger" })

自动补全对第一次输入有效,但对第二次输入无效…

以下是两个输入的html代码:
<div class="invalidite-section">
        <input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
    </div>
<div class="invalidite-section">
        <input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
    </div>

有什么建议吗?

您的目标是id #AdtFormModel_TemoinsVille,这是输入对吗?ID在页面上必须是唯一的。因此,它只会在它找到的第一个输入中工作。

您需要按类指定元素,然后自动补全应该在所有输入中工作。

试试这样:

   var auto5 = $('.form-control input').autocomplete({ // I suppose .form-control is a div that contains the input