Jquery自动填充显示名称并发送ID

问题描述 投票:1回答:2

如何更改我的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,
});
javascript jquery jquery-ui-autocomplete
2个回答
1
投票

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

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

您也可以使用格式为[{value: 'value', label: 'label'}]的选择数据,但使用这种方式,该字段将显示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">

0
投票

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

$("#searchSeller").autocomplete({
  messages: {
    noResults: 'No sellers with this ID.',        
  },
  minLength: 2,
  delay: 500,
  source: sellersID
});
© www.soinside.com 2019 - 2024. All rights reserved.