Reputation: 13325
How do you set a textbox value to the equivalent of DateTime.Now in Javascript? I tried these
$('#LastUpdatedTime').val('<%= System.DateTime.Now %>');
$('#LastUpdatedTime').val('<%= System.DateTime.Now.ToString() %>');
Both set the value to the literal string <%= System.DateTime... instead of the time.
Upvotes: 1
Views: 3323
Reputation: 2941
How about writing out the time on the main .aspx page in the header
<script type="text/javascript">
var now = <%= System.DateTime.Now %>;
</script>
and then doing
$('#LastUpdatedTime').val(now);
You just need to make sure that you name things appropriately so that the JS in the external file gets the value from the global scope.
Upvotes: 1
Reputation: 700212
You can't put server tags in a javascript file.
You have to put the code in a file that is handled by the ASP.NET engine, e.g. your .aspx file.
(It's possible to configure the server so that the ASP.NET engine also handles .js files, but that's not a good solution. Javascript files are cached more extensively than regular pages, so it's not certain that the server executes the code each time the file is used.)
Upvotes: 2
Reputation: 1602
Add a javascript function in the aspx which simply returns the server tag, then call this function from your .js file. i.e. in the ASPX add:
function GetTimeNow () { return '<%= System.DateTime.Now.ToString() %>';}
Upvotes: 2
Reputation: 34543
That code is fine. The problem is that your <%= System.DateTime.Now %>
code is not being parsed as server side code. What's the rest of the page look like?
Edit:
Since it's in an external JS file, you could always rename the ".js" file to ".aspx" so that ASP.Net would start processing it. Then you'd just have to change your <script>
tags to use the ".aspx" name instead.
The other option is to configure your server to send ".js" files through the ASP.Net handler.
Upvotes: 1
Reputation: 5587
Do you have them inside <script>
tags on the aspx page?
The aspx page should look something like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
//put your JAVASCRIPT here
$('#LastUpdatedTime').val('<%= System.DateTime.Now %>');
$('#LastUpdatedTime').val('<%= System.DateTime.Now.ToString() %>');
</script>
</form>
</body>
</html>
Upvotes: 1