javascript 强制用户从 JQuery UI 自动完成中选择并在选择后填充隐藏字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4502221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:54:38  来源:igfitidea点击:

Force a user to select from JQuery UI Autocomplete and populate a hidden field after selecting

javascriptjqueryjquery-uijquery-ui-autocomplete

提问by mhenry

I have a large HTML form that contains many fields that need an autocomplete for accounts. I tag these fields with the class AccountLookup and jQuery does the dirty work for the autocomplete:

我有一个大型 HTML 表单,其中包含许多需要自动完成帐户的字段。我用类 AccountLookup 标记这些字段,jQuery 为自动完成做了一些肮脏的工作:

$(".AccountLookup").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "Lookup.asmx/GetAccounts",
            data: "{ 'Search': '" + request.term + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.Value
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    },
    minLength: 3
});

Now, when a user selects something from the autocomplete I need it to populate a hidden field just BEFORE the tagged input field; probably using something like:

现在,当用户从自动完成中选择某些内容时,我需要它在标记的输入字段之前填充隐藏字段;可能使用类似的东西:

$(this).prev().val(item.Key);

How do I incorporate this functionality? Also, how do I force a user to select from the auto complete? (All the values are pre-defined, the user cannot add new ones.)

如何合并此功能?另外,如何强制用户从自动完成中进行选择?(所有值都是预定义的,用户无法添加新值。)

EDIT:As far as I understand from inspecting the DOM, the select option is currently filling in the hidden form field.

编辑:据我从检查 DOM 中了解到,选择选项当前正在填写隐藏的表单字段。

select: function (event, ui) {
    $(this).prev().val(ui.item.key);
}

采纳答案by Josiah Ruddell

$(".AccountLookup").autocomplete({
   /*...*/
}).result(function(event, item) {
   $(this).prev().val(item.Key);
});

You could also use a jQuery validateto ensure that the field is populated.

您还可以使用jQuery 验证来确保填充该字段。

回答by ek_ny

I know this is an old post--- but I ran into it in trying to solve a similar problem (forcing the user to select an item from the list)...

我知道这是一篇旧帖子——但我在尝试解决类似问题时遇到了它(强迫用户从列表中选择一个项目)......

        $("#ac").autocomplete({
            source: function (req, resp) {
                   //add code here...
            },
            select: function (e, ui) {
                $(this).next().val(ui.item.id);
            },
            change: function (ev, ui) {
                if (!ui.item)
                    $(this).val("");
            }
        });

回答by Saurabh

for force selection, you can use "change" event of Autocomplete

对于强制选择,您可以使用自动完成的“更改”事件

        var availableTags = [
            "ActionScript",
            "AppleScript"
        ];
        $("#tags").autocomplete({
            source: availableTags,
            change: function (event, ui) {
                if(!ui.item){
                    //http://api.jqueryui.com/autocomplete/#event-change -
                    // The item selected from the menu, if any. Otherwise the property is null
                    //so clear the item for force selection
                    $("#tags").val("");
                }

            }

        });

回答by Harry B.

I ran into this same problem quite awhile ago and some post helped me along with it. I have since modified the code as I found that there were cases I wanted one or more fields to fill in from the information returned. In the select option of the autocomplete I added a function.

不久前我遇到了同样的问题,一些帖子帮助了我。此后我修改了代码,因为我发现在某些情况下我希望从返回的信息中填写一个或多个字段。在自动完成的选择选项中,我添加了一个功能。

select: function (e, ui) {ReSetField({'txtID':'id','txtPrice':'price' [,etc...]}, ui)  }

The function "ResetFields" then takes in a JSON list of element names paired with fieldnamesand uses the fieldnamesto match the elementsin the ui object. The value can then be pulled from the ui item and put into the html element.

然后,函数“ ResetFields”接收一个与字段名配对的元素名称的 JSON 列表,并使用字段名来匹配ui 对象中的元素。然后可以从 ui 项中提取该值并将其放入 html 元素中。

    function ReSetField(_flds, _vals) {
  //Set up the flds to be reset with values passed in.  
  try {
    if (_flds != undefined) {
      if ($.type(_flds) == 'string') {
        _flds = JSON.parse(_flds);
      };
      var _fld = null;
      var _val = '';
      $.each(_flds, function (index) {
        if (index.length > 0) {
          _fld = '#' + index;   //Set the forms field name to set  
          _val = _flds[index]; //Pick up the field name to set the fields value 
          $fld = $(_fld);
          $fld.val(_vals.item[_val]); //Set the fields value to the returned value             
          }
        }
      })
    };
  }
  catch (e) {
    alert('Cannot set field ' + _fld + '.');
  } 
}

By sticking the "fieldlist" into the HTML element as an attribute like "fieldlist"and using a class like "comboBox"I can then use a single function to find all ComboBox elements and set up the autocomplete on a form reducing the amount of code required to handle 2 or more lookups on a form.

通过将“ fieldlist”作为“ fieldlist”之类的属性粘贴到HTML元素中并使用“comboBox”之类的类,然后我可以使用单个函数查找所有ComboBox元素并在表单上设置自动完成以减少代码量需要处理表单上的 2 个或更多查找。

回答by zsalzbank

For the selection action, try using the formatItemoption. You can format each result to have an onclick event that will populate the other textbox.

对于选择操作,请尝试使用该formatItem选项。您可以将每个结果格式化为具有将填充其他文本框的 onclick 事件。

For the forcing to select from autocomplete, you need to use the mustMatchoption.

要强制从自动完成中进行选择,您需要使用该mustMatch选项。

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions