the7k the7k - 29 days ago 5
Javascript Question

How to output name when id is entered

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];
}


But it's not working and it says:

ReferenceError: EmpID is not defined

Answer

Just change to

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

(no quotes around the element_id, as Daniel said)

And that's not how you declare an array. Overall, here's how your code should be like:

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]" />

You might also want to use oninput instead of onchange.

Here's a good piece of code, adding an event listener in the JavaScript part:

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" />