Javascript 使用不同的输入字段值自动完成

Javascript autocomplete with different input field value

我有以下 javascript 可以根据用户显示名称自动完成。问题是自动完成输入字段是显示名称。每个用户实际上都有一个用户 ID,但我想根据显示名称在自动完成中查找用户,但是当我提交表单时,我想提交用户 ID 本身。

<script>

$(document).ready(function() {
$("input#autocomplete").autocomplete({

source: [
"John Doe", 
"Another User", 

]

});

});

</script>

<input id="autocomplete" name="autocomplete"/>

谁能建议我该怎么做?理想情况下,在源代码中,是否有办法将用户 ID 也作为值,并以某种方式提交用户 ID 但带有显示名称?

您可以在数组中使用对象,而不是仅使用数组,这样您仍然可以搜索匹配的显示名称和 return 用户 ID

而不是:

source: [
"John Doe", 
"Another User", 

]

你可以做到:

var sourceValues = [
    {label: "John Doe",          value: 1},
    {label: "Another User",        value: 2},
]

$("#autocomplete").autocomplete({
    source: sourceValues.map(lang=>lang.label),
});

考虑以下示例。

$(function() {
  $("#user_name").autocomplete({
    source: [{
      label: "John Doe",
      value: 1001
    }, {
      label: "Jonny Appleseed",
      value: 1002
    },{
      label: "Jane Doe",
      value: 1003
    }],
    select: function(e, ui) {
      $("#user_name").val(ui.item.label);
      $("#user_id").val(ui.item.value);
      return false;
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<div>Name: <input id="user_name" /></div>
<div>ID: <input type="text" id="user_id" /></div>

这是基于这个例子:https://jqueryui.com/autocomplete/#custom-data

如果您定义了一个更复杂的源,您可以在 select 回调中使用它。 ui.item代表选中的对象。它有一个 labelvalue,您可以将其放入各个字段。