输入id时如何输出名称

时间:2016-11-11 01:28:49

标签: javascript

HTML

<input id="employee_id" onchange="fill_name(name[1],this.value);" type="text" name="employee_id[1]" />
<input id="name[1]" type="text" name="name[1]" />

的JavaScript

var EmpID = [];
var EmpID[7] = "John";
var EmpID[8] = "Dave";
var EmpID[9] = "Nik";

function fill_name(element_id, employee_id){
    document.getElementById(element_id).value = EmpID[employee_id];
}

但它没有用,它说:

ReferenceError: EmpID is not defined

3 个答案:

答案 0 :(得分:1)

只需更改为

document.getElementById(element_id).value = EmpID[employee_id];

(正如Daniel所说,element_id周围没有引号)

这不是你如何声明一个数组。总的来说,这是你的代码应该是这样的:

var EmpID = [];

EmpID[7] = "John";
EmpID[8] = "Dave";
EmpID[9] = "Nik";

function fill_name(element_id, employee_id) {  
    document.getElementById(element_id).value = EmpID[employee_id];
}
<input id="employee_id" onchange="fill_name('name[1]',this.value);" type="text" name="employee_id[1]" />

<input id="name[1]" type="text" name="name[1]" />

您可能还想使用oninput代替onchange

这是一段很好的代码,在JavaScript部分添加了一个事件监听器:

var employees = [
  "John",
  "Jack",
  "Joe",
  "Ian",
  "George"
];

document.getElementById("input").addEventListener("input", function() {
  document.getElementById("output").value = employees[this.value];
});
<input id="input" type="number" placeholder="Try a number from 0 to 4" />

<input id="output" type="text" />

答案 1 :(得分:1)

如果您有键值对 id -> name,则可以使用对象来存储数据。保持HTML和JavaScript 分开。带有 keyup事件示例可能如下所示:

&#13;
&#13;
var data = {
  // ...
  7: "Gustav",
  8: "Korben",
  9: "Wolther"
  // ...
};

var id = document.getElementById("id"),
  emp = document.getElementById("name");


id.addEventListener("keyup", function() {
  emp.value = data[this.value] || "No name with this id";
});
&#13;
<input type="number" id="id">
<input type="text" id="name">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以将员工ID存储在对象中,并使用eventListeners代替内联函数调用。

在这里演示:

&#13;
&#13;
var obj = {
 "EmpID[7]": "John",
 "EmpID[8]": "Dave",
 "EmpID[9]": "Nik"
}

var name_field = document.getElementById('name[1]');
var ID_field = document.getElementById('employee_id');
ID_field.addEventListener('keyup', fill_name, false);

function fill_name() {
  var request = ID_field.value.replace(/\[|\]/g, '');
  if (obj["EmpID["+request+"]"]) {
    name_field.value = obj["EmpID["+request+"]"];
  }
}
&#13;
<input id="employee_id" type="text" name="employee_id[1]" />

<input id="name[1]" type="text" name="name[1]" />
&#13;
&#13;
&#13;