简体   繁体   中英

javascript: easiest way to output names from student ID

My JS CODE

<script language="Javascript">
var data = {
   7: "Jack Black",
   8: "John Smith"
};

var id = document.getElementById("id"),
  emp = document.getElementById("name");
id.addEventListener("keyup", function() {
  emp.value = data[this.value] || "No name with this ID Number";
});
</script>

And in HTML i have

<input type="number" id="id" />
<input type="text" disabled="disabled" id="name" />

So what am i doing wrong, how come when i type 7, Jack Black doesn't appear inside the text box?

Many Thanks

The problem must be with the position of the script tag in the html file, you need to define the html element with id id before using the javascript to get the ID using document.getElementById("id") , this seems to be the only problem with the code.

Script content coming first and html after, causes the error

 <script language="Javascript"> var data = { 7: "Jack Black", 8: "John Smith" }; var id = document.getElementById("id"), emp = document.getElementById("name"); id.addEventListener("keyup", function() { emp.value = data[this.value] || "No name with this ID Number"; }); </script> <input type="number" id="id" /> <input type="text" disabled="disabled" id="name" />

If we reverse the order and define the html first, then the script, there is no error!

 <input type="number" id="id" /> <input type="text" disabled="disabled" id="name" /> <script language="Javascript"> var data = { 7: "Jack Black", 8: "John Smith" }; var id = document.getElementById("id"), emp = document.getElementById("name"); id.addEventListener("keyup", function() { emp.value = data[this.value] || "No name with this ID Number"; }); </script>

Your code works! But if you would like to use the arrows of the number input, use the change-event.

 // maybe it would be better to make an array var data = { 7: "Jack Black", 8: "John Smith" }; var id = document.getElementById("id"), emp = document.getElementById("name"); function changeValue() { emp.value = data[this.value] || "No name with this ID Number"; } // event listener if (id.addEventListener) { // new browsers id.addEventListener("keyup", changeValue, false); id.addEventListener("change", changeValue, false); } else if (id.attachEvent) { // IE <9, Opera <6 id.attachEvent("onkeyup", fchangeValue); id.attachEvent("onchange", fchangeValue); } else { // old browsers id.onkeyup = changeValue; id.onchange = changeValue; }
 <input type="number" id="id" /> <input type="text" disabled="disabled" id="name" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM