使用自动填充功能

时间:2017-04-14 08:09:17

标签: javascript jquery html input autocomplete

我创建了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 /名称列表。我试图在我的其他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 / names数组列表保留在JS中,而不是使用select /选项保存在HTML中。此外,Ids不一定是数字和字母/编号顺序,如Jsfiddle所示(我可以使用I12,如A123,SC001A等)。

提前致谢!

1 个答案:

答案 0 :(得分:1)

以下是一些需要做的更改。

使用onblur

<强> HTML

<input type="text" id="currentscholaridlist" onblur="idtoname()">
<br/>
<input type="text" id="currentscholarlist" onblur="nametoid(this)">
<br/>

源数组需要在函数之外。这是因为idtoname&amp; 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