我创建了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 / 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/>


源数组必须在函数之外。这是因为idtonamenametoid不在$(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

关于javascript - 具有自动完成功能的彼此依赖的输入文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43407697/

10-11 02:39
查看更多