2009年7月2日木曜日

getElementById使用時のobject required エラー

HTMLの方でちゃんとsIDというフィールドを作ったのに、

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

このgetElementByIdがIEでエラーになるのはどうしてでしょうか。

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

原因を見つけるのに数時間かかりましたが、このポストを見つけた人はもっと早く解決できるかも。

答えはHTMLのロードとJavascriptの実行のタイミングにありました。問題のgetElementById("sID") が呼び出される時にsIDというフィールドがロードされていなければエラーになるというわけです。ということはHTMLのロードを待ってからJavascriptを実行するようにすればいいわけです。例えば、

  <script type="text/javascript">
  function init() {
    //関数に入れる
     document.getElementById("sID").value = User;
  }
  .
  .
  .
  <body onLoad="init()"> <!-- HTMLのロードを待って呼び出す-->
     <input type="hidden" id="sID" name="sID" />

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