views:

903

answers:

3

In my MS SQL table, I read in an "time_zone" for a city from a record.

I then want to use this time zone in a Javascript function to create a digital clock for that city.

Currently I am trying to set the time_zone variable from

Here's a code snippet from Default.aspx:

            function showtime() {
                 zone(hiddenZone,clock);
            }
     window.onload = showtime;
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <span id="clock"></span>
    <asp:HiddenField ID="hiddenZone" runat="server" />
    <asp:Label Text="" ID="lblXml" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

The only C# I have in my Default.aspx.cs for is:

hiddenZone.Value=timeZone;

I've checked and timeZone has the correct value read in from the database.

The error message I receive from the JS in the "showtime" function is: "hiddenZone is undefined"

How can I get the "timeZone" C# variable into my Javascript and use it for the function?

A: 

Put it in server side tags,

        function showtime() {
             zone('<%= hiddenZone.Value %>',clock);
        }
Brandon
+3  A: 

You have to check against the hiddenZone ClientID.

function showtime() {
                 zone(
                      document.getElementById('<%=hiddenZone.ClientID%>'),
                      clock
                   );
            }

ASP.NET creates a new names for objects it creates on the HTML page, so they won't be the same as what you specify the id to be.

Kevin
With .NET 4.0's ClientIdMode property, you will have more flexibility in situations like this.http://www.dotnetcube.com/post/Overview-of-NET-40-features-e28093-ASPNET-40-ClientIDMode.aspx
DotnetDude
+1  A: 

You can use your existing code by replacing:

function showtime() {
    zone(hiddenZone, 'clock');
}

with

function showtime() {
    var elem = document.getElementById('<%= hiddenZone.ClientID %>');
    // if you are using ASP.NET AJAX use:
    // var elem = $get('<%= hiddenZone.ClientID %>');

    zone(elem.value, 'clock');
}

I'm not sure what your 'zone' function does either. But something like this may point you in the right direction if you are also having difficulties with it as well:

function zone(tz, dispID) {
    var elem = document.getElementById(dispID);
    // if you are using ASP.NET AJAX use:
    // var elem = $get(dispID);

    elem.innerHTML = tz;
}

Alternatively, if it were a public property on your page you can remove your reference to the asp:HiddenField and just use:

function showtime() {
    zone(<%= MyFormsTimeZoneProperty %>, clock);
}
Adam Markowitz