the7k the7k - 1 year ago 51
Javascript Question

How to display name when ID is entered

This is the HTML code:

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

and this is the JAVASCRIPT code:

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 Source

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 = [

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download