Run script on a runat=server control

cracker_chan picture cracker_chan · Sep 11, 2015 · Viewed 9.1k times · Source

how can you run a script on a control that has a runat=server attribute?

Removing the runat=server makes the script run smoothly, but I wouldn't be able to access the control.

Here's the script. Any idea?

<input runat="server" type="text" id="txthSchedTime" readonly="true" class="asclock" style="width:100px; background-color:lightyellow" onclick="setTimePicker();" />
<script>
$("#txthSchedTime").AnyTime_picker(
{
format: "%h:%i %p", labelTitle: "Schedule Time",
labelHour: "Hour", labelMinute: "Minutes"
});
</script>

thanks

Answer

Jad Chahine picture Jad Chahine · Sep 11, 2015

You can call the function from code behind like this :

yourForm.aspx.cs:

    protected void txthSchedTimeEvent(....)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "myFunction();", true);
    }

yourForm.aspx

        <html xmlns="http://www.w3.org/1999/xhtml">
            <head id="Head1" runat="server">
                <title>My Page</title>
                <script type="text/javascript">
                    function myFunction(){
                    $("#txthSchedTime").AnyTime_picker(
                    {
                    format: "%h:%i %p", labelTitle: "Schedule Time",
                    labelHour: "Hour", labelMinute: "Minutes"
                    });
                    }
                </script>
            </head>
            <body>
                <form id="form2" runat="server">
                <table>
                    <tr> <td> 
                     <asp:TextBox ID="txthSchedTime" runat="server" 
                        style="width:100px; background-color:lightyellow">
                     </asp:TextBox>
                    </td> </tr>
                </table> 
                </form>
            </body>
        </html>