I'm trying to display the current date in an ASP.NET label using JavaScript and C#. Here's what I have:
C#:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "GetDate()", true);
}
JS:
<script type="text/javascript">
function GetDate()
{
var dt = new Date();
var element = document.getElementById("MainContent_FormView1_Label1");
element.text = dt.toDateString();
}
</script>
ASP.NET:
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Date", "{0:d}") %>'></asp:Label>
Can anyone see where I'm going wrong? Also, can the JS be run when the page loads without using the C# Page_Load method? I picked up the RegisterStartupScript elsewhere but I don't really understand it.
Thanks, Liam
Try using element.innerText = dt.toDateString();
instead.
Also, you don't need to use RegisterStartupScript
. You can just call the getDate()
function in the onLoad
event.
<script type="text/javascript">
window.onload = function(){
getDate();
};
function getDate()
{
var dt = new Date();
var element = document.getElementById("MainContent_FormView1_Label1");
element.text = dt.toDateString();
}
</script>
However, you might want to read this SO thread for best practice in using window.onload
, or consider using a framework such as jQuery and its document.ready