我创建了 2 个输入文本,一个是 ID,另一个是 Name。如果我在第一个输入文本中键入 ID,然后按 Tab 键或单击第二个输入文本(在 HTML 中使用 onfocusout),则第二个输入文本将自动填充分配给该 ID 的名称。例如,输入 ID“001”将显示“Elnora”。同样,在第二个输入文本中键入“Soo”(并按 Tab 键)将在第一个输入文本中显示“010”。基本上它是基于索引号的一对一映射。正如您在我的 Jsfiddle 中看到的那样,它工作得完美无缺。 .
var scholaridlists = ["001","002","003","004","005","006","007","008","009","010"];
var scholarlists = ["Elnora","Henry","Scotty","Bruna","Shirley","Modesto","Lissa","Davida","Margherita","Soo"];
function idtoname() {
var ids=document.getElementById("currentscholaridlist").value;
var a = scholaridlists.indexOf(ids);
document.getElementById("currentscholarlist").value =scholarlists[a];
}
function nametoid() {
var names=document.getElementById('currentscholarlist').value;
var b = scholarlists.indexOf(names);
document.getElementById('currentscholaridlist').value = scholaridlists[b];
}
但是,由于并非每个人都记得任何人的 ID 和/或姓名,因此我还想实现自动完成功能,以便每当有人输入 ID/姓名时,都会出现建议的 ID/姓名列表。我正在尝试使用 JQueryUI 自动完成,就像我的其他 Jsfiddle 中那样。 。自动完成功能有效,但按 Tab/单击其他输入文本不会显示其他分配的配对。
$( function() {
"use strict";
var scholaridlists = ["001","002","003","004","005","006","007","008","009","010"];
$( "#currentscholaridlist" ).autocomplete({ source: scholaridlists, minLength:3, maxShowItems:5 });
var scholarlists = ["Elnora","Henry","Scotty","Bruna","Shirley","Modesto","Lissa","Davida","Margherita","Soo"];
$( "#currentscholarlist" ).autocomplete({ source: scholarlists, minLength:3, maxShowItems:5 });
} );
function idtoname() {
var ids1=document.getElementById("currentscholaridlist").value;
var a = scholaridlists.indexOf(ids1);
var ids2= a;
document.getElementById("currentscholarlist").value =scholarlists[ids2];
}
function nametoid() {
var names1=document.getElementById('currentscholarlist').value;
var b = scholarlists.indexOf(names1);
var names2 = b;
document.getElementById('currentscholaridlist').value = scholaridlists[names2];
}
如果有人能解决这个问题,我更希望将 Ids/names 数组列表保留在 JS 中,而不是使用 select/option 保留在 HTML 中。此外,Id 不一定是数字和字母/编号顺序,如 Jsfiddle 中所示(我可以使用 A123、SC001A 等 Id)。
提前致谢!
最佳答案
这里需要进行一些更改。
使用onblur
HTML
<input type="text" id="currentscholaridlist" onblur="idtoname()">
<br/>
<input type="text" id="currentscholarlist" onblur="nametoid(this)">
<br/>
源数组需要位于函数之外。这是因为 idtoname
和 nametoid
不在 $(function(){..} 范围内)
。所以他们将无法访问该数组
JS
var scholaridlists = ["001", "002", "003", "004", "005", "006", "007", "008", "009", "010"];
var scholarlists = ["Elnora", "Henry", "Scotty", "Bruna", "Shirley", "Modesto", "Lissa", "Davida", "Margherita", "Soo"];
$(function() {
// Rest of the code
});
function idtoname() {
// rest of the code
}
function nametoid() {
// rest of the code
}
关于javascript - 通过自动完成功能输入相互依赖的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407697/