jQuery 自动完成选择填充其他字段

rya*_*yan 1 javascript jquery json jquery-ui autocomplete

我调用远程数据源并返回json。在我选择一个项目后,select:回调选项只允许我使用项目的标签和值,但我还想使用我的 json 对象的其他属性来自动填充其他字段。

有没有一种方便的方法来做到这一点,我错过了?到目前为止我看到的选项是......

  1. 全局缓存ajax响应json对象,select后引用这个全局对象
  2. 使用项目的值或标签在选择时重新查询数据库

对其中任何一个都不是特别满意。想法?

编辑 我忘了我在使用 $.map

$('#accountName').autocomplete({
  source: function (request, response) {

      $.getAccountsByNameLike(request.term, function (data) {
          response($.map(data, function (item) {
              return {
                  label: item.Name + ' (' + item.Address.City + ', ' + item.Address.StateOrProvince + ')',
                  value: item.AccountId,
                  // Added to fix issue
                  raw: item
              }
          }));
      }, function (error) {
          // async kickoff a log to logging server service...
          alert("There was a problem while trying to retrieve account names. Please contact support");
      });
Run Code Online (Sandbox Code Playgroud)

Eon*_*dan 5

是什么让您认为您只能使用标签和价值?

select: function (event, ui) {
       foo = ui.item.label;
        $("#bar").val(ui.item.id);
       baz = (ui.item.JsonField);
    }
Run Code Online (Sandbox Code Playgroud)