0

By loading the following simple javascript and html, I get the famous

Uncaught TypeError: Cannot read property 'value' of null

during the window.onload event if and only if I include the parenthesis on the event handler assignment as shown. If I change that line to read

window.onload = verifyAdd;

(no parenthesis) I do not get the error in my chrome/firefox debug panels. Why, exactly? Is there a functional difference?

Javascript:

window.onload = verifyAdd();
function verifyAdd()  {
    var first;

    first = document.getElementById("txtFirstName").value;
}

HTML:

<html>
<head>
    <script type="text/javascript" src="./frobozz.js"></script>
</head> 
<body>
    <input type=text id=txtFirstName name=txtFirstName size=30 onchange=verifyAdd() />
</body>
</html>
Omortis
  • 1,334
  • 19
  • 44
  • Without `()` means you are assigning the function reference to `.onload`. Huge difference. (In JavaScript, functions are objects so you can do that) – Derek 朕會功夫 Aug 02 '14 at 21:51
  • `window.onload = verifyAdd` overrides the window.onload function to be your verifyAdd function. After doing that doing `window.onload()` would call your verifyAdd function. – Joe Dyndale Aug 02 '14 at 21:52
  • Great - thanks! I must have missed that in my book and on w3... – Omortis Aug 02 '14 at 23:11

1 Answers1

1

By doing:

window.onload = verifyAdd();

you are assigning the result of the execution of verifyAdd()which is undefined.

By doing

window.onload = verifyAdd;

you are just storing the function verifyAdd in order to execute it later.

The error is due to the body of verifyAdd:

 first = document.getElementById("txtFirstName").value;

You don't wait until your document is loaded (because you are executing the function inmediatly) so the variable document is null. Then you are dealing with null references, hence the error message.

Marcos
  • 4,643
  • 7
  • 33
  • 60