Melodie Gauthier Melodie Gauthier - 16 days ago 6
Javascript Question

jquery autocomplete - string array

My web form model(AdtFormModel) has this variable:

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


I use a list because I want the user to be able to dynamically add more 'TemoinsVille' in the form. For now I have two textboxfor, when I fill both of them, my controller receives a string list with 2 items in it. I will add the feature to dynamically add TemoinsVille later.

In my form, I want to use an auto-complete field for this TemoinVille variable. I use a method called 'AutocompleteTous' that works, I use it somewhere else in the form. I don't know how to write the script so that the autocomplete works for a second TemoinVille input.

My JQuery code is:

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");
};


In my view, I have t TemoinVille textboxfor inputs:

@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" })


the autocomplete works for the first input, but not for the second...

Here is the html code for the two inputs:

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


Any suggestions?

Answer

You are targeting an id #AdtFormModel_TemoinsVille, that's the input right? The ID must be unique on page. So it will work only on first input it finds.

You need to target the elements by class, then the autocomplete should work in all inputs.

try something like this:

   var auto5 = $('.myInput').autocomplete({
Comments