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

发布于 2024-10-09 02:17:41 字数 1207 浏览 0 评论 0原文

我有一个大型 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
});

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

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

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

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

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

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:

$(".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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

万劫不复 2024-10-16 02:18:01

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

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

然后,函数“ResetFields”接收与字段名称配对的元素名称的 JSON 列表,并使用字段名称来匹配元素< /strong> 在 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 + '.');
  } 
}

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

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 fieldnames and uses the fieldnames to match the elements in the ui object. The value can then be pulled from the ui item and put into the html element.

    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.

夜空下最亮的亮点 2024-10-16 02:17:59

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

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

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

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

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

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

怼怹恏 2024-10-16 02:17:58

对于强制选择,可以使用 Autocomplete 的 "change" 事件

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

            }

        });

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

            }

        });
羁绊已千年 2024-10-16 02:17:54
$(".AccountLookup").autocomplete({
   /*...*/
}).result(function(event, item) {
   $(this).prev().val(item.Key);
});

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

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

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

烟─花易冷 2024-10-16 02:17:50

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

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

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("");
            }
        });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文