Jquery 自动完成显示名称并发送 ID

Jquery Autocomplete display names and send Id

如何更改我的 jQuery 自动完成功能以使用 ID 而不是我的值? 我想显示名称列表,但使用 Id 值发送搜索。现在它可以正常使用名称,但我认为如果它尝试找到一个唯一值作为 ID 会更有效。

$.getJSON('Dashboard/CompaniesWithId', function (data) {
  $.each(data, function (i, item) {
    sellers[i] = item.Name;
    sellersID[i] = item.Id;
  });
}).error(function () {
  console.log("error loading seller to the autocomplete");
});

$("#searchSeller").autocomplete({
  messages: {
    noResults: 'No sellers with this name',        
  },
  minLength: 2,
  delay: 500,
  source: sellers,
});

我对你的后端一无所知。但是假设它接受您的搜索参数的 ID,将 source 值更改为 sellersID 是否会解决您的问题? sources 后面还有那个额外的逗号。这会给你带来麻烦。

$("#searchSeller").autocomplete({
  messages: {
    noResults: 'No sellers with this ID.',        
  },
  minLength: 2,
  delay: 500,
  source: sellersID
});

您可以添加隐藏字段并使用 on select 事件将隐藏字段的值设置为 selected id

http://api.jqueryui.com/autocomplete/#event-select

您也可以使用格式为 [{value: 'value', label: 'label'}] 的 selection 数据,但使用这种方式,该字段将显示 id 而不是标签

var availableTags = [
      {id: 1, label: "ActionScript"},
      {id: 2, label: "Ruby"},
      {id: 3, label: "Scala"},
      {id: 4, label: "Scheme"}
    ];
    availableTags2 = [
      {value: 1, label: "ActionScript"},
      {value: 2, label: "Ruby"},
      {value: 3, label: "Scala"},
      {value: 4, label: "Scheme"}
    ];
    $( "#a" ).autocomplete({
      source: availableTags,
      select: function( event, ui ) {
        $('#tosend').val(ui.item.id);
      }
    });
    $( "#b" ).autocomplete({
      source: availableTags2
    });
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
     src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
     integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
     crossorigin="anonymous"></script>
id to send<br>
<input type="text" name="tosend" id="tosend"><br><br>
type below<br>
<input id="a"><br>
<br>
<br>
using value instead of id<br>
<input id="b">