tags:

views:

203

answers:

3

Here is the best example that I can create. The value of the innerHTML appears in the alert triggered by the onload function. When it hits the document.write, the same innerHTML becomes null. Any ideas on how to get the innerHTML to appear outside the onload function? I've tried global variables and even copying the value to hidden inputs and it still comes up null.

<html>

<head>

<script language='javascript'>
 function onload_function() {
  alert(document.getElementById("sample_size").innerHTML);
 }

 document.write("this is a test: " + document.getElementById("sample_size").innerHTML);
</script>

</head>

<body onload='onload_function()'>
 <form name='form_test'>
  <table border='0' cellpadding='0' cellspacing='0'>
   <tr>
    <td id='sample_size' style='display:none'>16</td>
   </tr>
  </table>
 </form>
</body>

</html>
A: 

instead of using a global var try putting it into a hidden input element with a unique id so you can get it with the other function using getElementByID

Brandon H
That's a horrible idea. You're trading design aspect that is only questionably a minor issue, for an incredibly slow (in comparison) work around implementation.
Justin Johnson
now that he's added source code i have something else to go on. thanks for the down vote.
Brandon H
A: 

Without the source code, we can't really help you.

There are three possiblities here.

The variable might not actually be global.
Did you declare it with the var keyword inside the function?

The variable might be assigned to undefined elsewhere.

You may have mispelled its name.

Check the DOM tab in Firebug and see whether the variable is there and what its value is.

SLaks
+1  A: 

You should try adding the script:

<script language='javascript'>
 document.write("this is a test: " + document.getElementById("sample_size").innerHTML);
</script>

in the HTML <body> instead of the in <head>. The value/page isn't loaded yet when that javascript is evaluated in the header.

jeffl8n