2017-04-14 61 views
0

我创建了2个输入文本,一个是ID,另一个是Name。如果我在第一个输入文本中输入一个ID,然后按Tab或单击第二个输入文本(使用HTML中的onfocusout),第二个输入文本将自动填入分配给该ID的名称。例如,键入ID'001'将显示'Elnora'。同样,在第二个输入文本中输入'Soo'(并按下标签)将在第一个输入文本中显示'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 /名称的建议名单将出现。我试图在我的其他Jsfiddle中使用JQueryUI自动完成。自动完成功能可以正常工作,但按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 /名称数组列表仍然是JS,而不是使用选择/选项HTML。另外,Ids不一定是按照Jsfiddle(我可以使用I123,如A123,SC001A等)显示的数字和字母/编号顺序。

在此先感谢!

回答

1

这里有几个需要改变的地方。

使用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 
    } 

DEMO

+0

哇访问,没想到该解决方案是如此简单。非常感谢你@brk!无论如何,以前我尝试将数组移到外面,但它不起作用。也许这与onblur vs onfocusout有关?另外,出于好奇,如果你碰巧知道,为什么idtoname()在括号内没有'this'而不是nametoid(this)?对不起,因为我对这个JS/HTML的东西相当新。再次感谢! –