Saturday, January 15, 2011

IE8 : Object doesn't support this property or method

The problem
Try to load following html to IE8 then insert some text to the input box and click the button. It should just alert the text you had key in but it give a javascript error "Object doesn't support this property or method". Below code work perferly on FF 3.5.3.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>ID Test</TITLE>
<script type="text/javascript">
function testnow()
{
 inputvalue = document.getElementById('inputvalue').value;
 alert ("input value is ["+inputvalue+"]");
}
</script></HEAD>
<BODY>

<H3>Input Text</H3>
<input id="inputvalue" type="tet"></input>
<BR/>
<button onclick="testnow()">click me</button>
</BODY></HTML>

The catch
The cause of this js error is the HTML ID of the input (which is "inputvalue") is same as the js variable name used in testnow() function. IE8 seem can access the HTML element just use the ID directly. Try to replace testnow() function codes with this code alert (inputvalue.value); . It work in IE8! of course, will not work in FF3.5.3.

The solution
  1. While declare a js variable, use the var keyword (e.g. var inputvalue="").
  2. Do not use the same name at both HTML ID and javascript variable name.
  3. Best practice, give better name for you variable like txtInputValue.
Environment

  • Broswer : Internet Explorer 8.07600.16385
  • OS: Window 7
  • HTML Doc Type: DTD HTML 4.01
     

      No comments:

      Post a Comment