2017-04-14 66 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的東西相當新。再次感謝! –