0

here is my issue:

when i say getelementbyid("table1") it says"Uncaught TypeError: Cannot set property 'innerHTML' of null"

i am rendering a dynamic table via java script asshown below:

function mainProcessing()
{
        <% ProductController pc=new ProductController();%>

        var val = <%=pc.doTask()%>
        var jobj=JSON.stringify(val);
        document.write(jobj);
        alert(jobj);

         var obj=JSON.parse(jobj);
        alert("jobj");
        alert(obj.toString());
        var object = eval("(" + jobj+ ")");

        alert("this part is done");
        return object;
}
function drawtable()
{
    var JSONObj=mainProcessing();
    var tablecontents = "";
    for (var i = 0; i < 5; i ++)
   {
      tablecontents += "<tr>";
      tablecontents += "<td>" + i + "</td>";
      tablecontents += "<td>" + i * 100 + "</td>";
      tablecontents += "<td>" + i * 1000 + "</td>";
      tablecontents += "</tr>";
   }

 document.write(JSONObj.toString());       
    alert("just outside nested loop");
   document.getElementById("table1").innerHTML = tablecontents;
}

for testing i have inserted randome values in the table.

and that html part goes like this:

<title>Indian Divine !!!</title>
</head>
<body onload="drawtable()">
<center>
<h1>my name is jobj</h1>
    <table id="table1">

    </table>
</center>
</body>
</html>

the browser user is Chrome. IDE Eclips Juno

Mayur Gupta
  • 762
  • 3
  • 8
  • 23

2 Answers2

3

You can not use document.write after the page load. It replaces the content. If you are trying to see what is in it, use console.log(jobj);

Second, if you plan on using this code with IE, you can't set the tables innerHTML.

Third, do not use eval() to convert JSON. Use JSON.parse()

Community
  • 1
  • 1
epascarello
  • 204,599
  • 20
  • 195
  • 236
2

document.write(mayur) replaces the whole document (including the table) with the value of mayur, because you are calling it after the document was loaded. At the moment you are trying to access the element with ID table1, it does not exist anymore.

Solution: Don't use document.write.

More info: MDN - document.wite

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143