views:

65

answers:

3

I have a <script> that contains this line:

var tbl = document.getElementById("<%= this.tblSelection.ClientID %>");

... but tbl always ends up being set to null.

The table is declared like this:

<asp:Table ID="tblSelection" runat="server" CellPadding="2" CellSpacing="0"
    cols="1" style="position: absolute; top: 0%; right: 0%">

Both the script and the table are in the same master page file.

What could be causing this?

EDIT: I should mention that this script is executed on onload

+2  A: 

I am guessing your JavaScript code is executing before your browser has a chance to fully render the table. At this point, the DOM of the page will not be complete and the getElementByID function will not be able to find the table because it doesn't exist yet!

Do this experiment:

<head runat="server">
<title></title>

<script language="javascript">

    function showTable() {

        var tbl = document.getElementById("<%= this.tblSelection.ClientID %>");

        alert(tbl);
    }

    showTable();

</script>

This will show you "null" when your page first loads. If you add a button to call this method again, however, you'll see that tbl gets populated.

<input type="button" value="CheckTable" onclick="showTable();" />
MrGumbe
Hmm, okay. Do you know how to access the DOM in the onload event handler, or is there any alternative?
Giffyguy
Sure. The page body's OnLoad event handler fires AFTER the body renders, so the object is available. Try: <body onload="showTable();">The other option, which isn't nearly as elegant, is to put your Javascript block AFTER the body of the page.
MrGumbe
+1  A: 

Nick is correct. The table is not parsed/constructed yet. Try to move getElementById code to document.ready event. BTW, JQuery provide nice wrapper around document events and more.

Here is code snippet:

$(document).ready(function()
{
    $get('table-id').doManipulation();
});
Valera Kolupaev
document.ready doesn't seem to work either. Still null.
Giffyguy
Did MrGumbe solution helped? If so, probably your's table is placed in update panel, or something that loads after document-ready.Btw, did you installed JQuery? $(document).ready is a JQuery extension.
Valera Kolupaev
+1  A: 

MrGumbe and Valera are right about the timing of your Javascript. But I've seen this happen for another reason. We have had instances where server-side logic set tblSelection.Visible=false which means it isn't even emitted to the browser. Client-side code like yours runs looking for the ID and bang.

n8wrl