Reputation: 21
I am attempting to set text in a SPAN element from JavaScript and it is not working. Any help would be greatly appreciated.
The HTML on the asp.net page is as follows:
<div class="TimerRowDetail TimerDaysDetail">
<asp:Label ID="lblDays" runat="server" Text="yyy" ClientIDMode="Static"></asp:Label>
</div>
The generated HTML is as follows:
<div class="TimerRowDetail TimerDaysDetail">
<span id="lblDays">yyy</span>
</div>
My JavaScript is as follows:
var lblDays = $("#<%=lblDays.ClientID%>");
if (lblDays != null)
{
alert("OK");
lblDays.innerHTML = "XXX";
}
I see the OK alert but the text never changes to XXX.
I am testing with both IE 9 and FireFox 9.0.1.
Thanks. EDIT:
Ok, I am not suggesting the answer icarus gave is incorrect, only that it is not working in my environment.
Below is the source for the page including the script I am using. It does not work on my machine.
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeBehind="DatePlay.aspx.cs"
Inherits="CountDownClock.WebUI.DatePlay"
%>
<!DOCTYPE html >
<html lang="en">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
var lblDays = $("#<%=lblDays.ClientID%>");
lblDays.html("XXX");
alert("done");
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblDays" runat="server" Text="yyy" ClientIDMode="Static"></asp:Label>
</form>
</body>
</html>
Again I am using IE 9 and FireFox on a Windows 7 box with HTML5 specified in the
Any suggestions would really be appreciated.
Upvotes: 1
Views: 4592
Reputation: 5662
You should use $(document).ready()
to run your code once the DOM has loaded and the element can be accessed.
<script type="text/javascript">
$(document).ready(function() {
var lblDays = $('#<%=lblDays.ClientID%>');
lblDays.html("XXX");
});
</script>
Upvotes: 1
Reputation: 11598
jQUery selector returns an HTML list, not an element, even if it only selects 1 element.
So:
$(lblDays).html('XXX')
or
lblDays[0].innerHTML = 'XXX'
Also, when the script is being executed, the label doesn't exist in the DOM yet. you should wrap it with
$(document).ready(function(){});
or move the script to the end of the body.
Upvotes: 0
Reputation: 63966
Try this:
$(document).ready(function() {
var lblDays = $("#<%=lblDays.ClientID%>");
if (lblDays != null)
{
lblDays.html("XXX");
}
}
Upvotes: 0