jQuery UI-自动完成功能选择值而不是标签

这是我的编码

$("#txtBox").autocomplete({
                source: function (request,response) {
                    $.ajax({
                        type: "POST",url: '@Url.action("Get","Ctrl")',dataType: 'json',data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",contentType: "application/json;charset=utf-8",success: function (data) {
                            var transformed = $.map(data,function (item) {
                                return {
                                    label: item.Name,value: item.Id
                                };
                            });
                            response(transformed);
                        },error: function() {
                            alert('error');
                        },});
                },minLength: 3,select: function (event,ui) {
                    console.log('ui.item.label',ui.item.label);
                    $('#txtBox').val(ui.item.label);
                },focus: function (event,ui) {
                    console.log('ui.item.label - focus',ui.item.label);
                    $('#txtBox').val(ui.item.label);
                }
            });
        });

我从c#控制器获取Json的名称和ID。我想在自动完成文本框中显示名称,然后在保存时将其发送回后端,我想发送名称的ID。但是现在,当我键入名称并从建议列表中选择名称时。该ID将显示在文本框中而不是名称中。我在哪里弄错了。有人可以指导我吗?

wangshaozhuang 回答:jQuery UI-自动完成功能选择值而不是标签

我建议您保留两个<input />,一个是type = text,另一个是type = hidden。您可以在type = text上初始化自动完成功能,并在type = hidden中设置该值,在服务器中,您可以访问hidden类型的值。

例如

<input type="text" id="txtBox" name="label" />
<input type="hidden" id="valBox" name="value" />

$("#txtBox").autocomplete({
                source: function (request,response) {
                    $.ajax({
                        type: "POST",url: '@Url.Action("Get","Ctrl")',dataType: 'json',data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",contentType: "application/json;charset=utf-8",success: function (data) {
                            var transformed = $.map(data,function (item) {
                                return {
                                    label: item.Name,value: item.Id
                                };
                            });
                            response(transformed);
                        },error: function() {
                            alert('error');
                        },});
                },minLength: 3,select: function (event,ui) {
                    console.log('ui.item.label',ui.item.label);
                    $('#txtBox').val(ui.item.label);
                    $('#valBox').val(ui.item.value);
                },focus: function (event,ui) {
                    console.log('ui.item.label - focus',ui.item.label);
                    $('#txtBox').val(ui.item.label);
                }
            });
        });

在您的控制器中,您可以访问两个值Request [“ label”]和Request [“ value”]

本文链接:https://www.f2er.com/3168379.html

大家都在问