Getting Javascript error on asp.net web form: document.getElementById is null or not an object

Hello I am getting this error when my javascript code tries to set the text of and asp.net label: "document.getElementById(...) is null or not an object"

At first, it doesnt seem to cause any problems because the label does get set, but it seems to be locking up the page.  Its a pretty simple function, on the page load event, I set an asp.net label to the current time, I have always noticed the Warning icon in the bottom left corner, but ignored it because the page loaded fine.  I have noticed the same message on my other asp.net pages as well, any ideas.
<script> 
function set_current_time(){
var Digital=new Date()
var hours=Digital.getHours()
var minutes=Digital.getMinutes()
var dn="AM"
document.getElementById("lblc_time").innerText = hours+":"+minutes+" "+dn
}
</script> 
<body onload="set_current_time();" >
<asp:label id="lblc_time" runat="server" Font-Bold="True" Font-Size="35pt" ForeColor="Red">4:00 PM</asp:label>
</body>

Open in new window

tentavariousAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Michel PlungjanIT ExpertCommented:
most likely because ASP makes a completely different ID out of your ID
Have a look in the view-source for the actual ID or use the ASP to give you the client ID
0
 
Snarf0001Connect With a Mentor Commented:
asp.net changes the ids of server controls and adds prefixes to make sure there are no conflicts.

You need to use the .ClientID property:

document.getElementById('<% lblc_time.ClientID %>').innerText......
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Michel PlungjanIT ExpertCommented:
And this will work in more browsers (and show correct time too)

function set_current_time(){
var Digital=new Date()
var hours=Digital.getHours()
var minutes=Digital.getMinutes()
if (minutes<10) minutes="0"+minutes
var dn=(hours>=13)?"PM":"AM";
if (hours>=13) hours-=12
document.getElementById("<% lblc_time.ClientID %>").innerHTML = hours+":"+minutes+" "+dn
}

0
 
Michel PlungjanIT ExpertCommented:
btw why not

<asp:label id="lblc_time" runat="server" Font-Bold="True" Font-Size="35pt" ForeColor="Red">
<script>
var Digital=new Date()
var hours=Digital.getHours()
var minutes=Digital.getMinutes()
if (minutes<10) minutes="0"+minutes
var dn=(hours>=13)?"PM":"AM";
if (hours>=13) hours-=12
document.write(hours+":"+minutes+" "+dn);
</script>
</asp:label>

Open in new window

0
 
tentavariousAuthor Commented:
I left out a lot of extra code but I need to set the asp.net label to the correct time, there is no way around it.  Also I get the same error why I tried using the <%= %> blocks.  None of the suggestions worked also I am using asp.net 1.1 so I dont think there is a  ClientIDMode property.
0
All Courses

From novice to tech pro — start learning today.