简体   繁体   English

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

[英]Javascript autocomplete with different input field value

I have the following javascript that autocompletes based on a users display name.我有以下 javascript 根据用户显示名称自动完成。 Problem is that the autocomplete input field is the display name.问题是自动完成输入字段是显示名称。 Each user actually has a user id, but I want to look up the user in the autocomplete based on the display name but when I submit the form I want to submit the user ID itself.每个用户实际上都有一个用户 ID,但我想根据显示名称在自动完成中查找用户,但是当我提交表单时,我想提交用户 ID 本身。

<script>

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

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

]

});

});

</script>

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

Can anyone suggest how i can do this?谁能建议我如何做到这一点? Ideally in the source, is there a way to have the user ID as the value too and somehow have the user ID submitted but with display name?理想情况下,在源代码中,有没有办法将用户 ID 也作为值,并且以某种方式提交了用户 ID 但带有显示名称?

instead of using just an array you could use object inside the array so you can still do your search for matching display name and return the user id您可以在数组中使用 object 而不是仅使用数组,这样您仍然可以搜索匹配的显示名称并返回用户 ID

instead of:代替:

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

]

you can do:你可以做:

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

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

Consider the following example.考虑以下示例。

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

This is based on this example: https://jqueryui.com/autocomplete/#custom-data这是基于这个例子: https://jqueryui.com/autocomplete/#custom-data

If you define a more complex source, you can make use of it in the select callback.如果定义更复杂的源,可以在select回调中使用它。 ui.item represents the object selected. ui.item代表选择的 object。 It has a label and value that you can put in various fields.它有一个label和可以放在各个领域的value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM