2009年7月2日木曜日

Beware: getElementById object required error

Why does this Javascript statement cause an object required error in IE

  <script type="text/javascript">
  document.getElementById("sID").value = User;

when there is an object by that name?

  <input type="hidden" id="sID" name="sID" />

It took me several hours to figure it out. Maybe this post will help those who will follow.

The answer is that you need to make sure that when getElementById("sID") is called, an object by that name has already been created. Yes, the HTML section of your code must load first before the Javascript code can be executed. So, a solution is as follows:

  <script type="text/javascript">
  function init() {
    //put it in a function
     document.getElementById("sID").value = User;
  }
  .
  .
  .
  <body onLoad="init()"> <!-- call the function after HTML loads-->
     <input type="hidden" id="sID" name="sID" />

0 件のコメント: