简体   繁体   中英

“Uncaught TypeError: Cannot read property 'Name' of undefined” when triggered a function

EDIT: I found that the code is working fine and nothing is wrong. It's myself that was blurred. Sorry for not being cautious.

I have a HTML file with a form containing a textbox with ID #StuIDtxt.

Also there is a few JavaScript, and here is a code in my file. The function getResult() would be triggered when the form is submitted.

function getResult(){
  var StuID = document.getElementById('StuIDtxt').value;
  document.getElementById('name').innerHTML = result[StuID].Name;
  return false;
}

There is also a variable name 'result' storing array parsed from JSON.

When I fill the textbox with '10001' and submit the form, JavaScript console said

Uncaught TypeError: Cannot read property 'Name' of undefined

However typing

document.getElementById('name').innerHTML = result['10001'].Name;

in console result in successful execution as expected.

Did I do anything wrong in the function?

Live web here: https://srakrn.com/satitnpru/announce

The JSON retrieved from https://srakrn.com/satitnpru/announce/result_demo.json does not contain any id of 10001 . If I try 00001 the error does not occur. Change like this:

function getResult(){
  var StuID = document.getElementById('StuIDtxt').value;
  if ( StuID != null && StuID.trim() != "" )
  {
       if ( typeof result[StuID] != "undefined" )
           document.getElementById('name').innerHTML = result[StuID].Name;
       else
           alert("Unknonw ID: " + StuID);
  }
  return false;
}

In your code, you assume that the given ID will always exist in result and directly reference Name . In case, StuID doesn't exist, this will cause a runtime error.

Maybe it's because '10001' doesn't exist

here is the log from the result var

http://prntscr.com/9mdsjv

I used '00020' and its OK

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