Search code examples
javascriptasp.netdom-eventsclient-side

OnClientClick event in In ASP.NET


I'm using ASP.NET to pass a value to a JavaScript function and, for some reason I haven't been able to determine, it isn't working when I try to pass in a value from another control. Instead, it acts like there is a syntax error and it just submits back to the main form.

Does anyone know why?

Example:

<asp:TextBox ID="txtToSay" runat="server" Text="Something"></asp:TextBox>

<asp:Button runat="server" ID="btnSaySomething1" Text="Say Something"
OnClientClick="saySomething(<%=txtToSay.Text%>);"  /> <!-- doesn't work -->

<asp:Button runat="server" ID="btnSaySomething1" Text="Say Something"
OnClientClick="saySomething('<%=txtToSay.Text%>');"  /> <!-- doesn't work -->

<asp:Button runat="server" ID="btnSaySomething2" Text="Say Something"
OnClientClick="saySomething('Something');"  /> <!-- works -->

<script type="text/javascript">
    function saySomething(txt){
        alert(txt);
    };
</script>

Additional Information:

Web Application running on .NET 4.0 Language: C#

Update:

After working with this a while, I've determined that you can't use <%%> tags in ASP controls. Additionally, if you're looking for dynamic evaluation of control values AVOID AVOID AVOID using <%=someControl.Text%> or similar constructs since they are only evaluated once a request is submitted to the server. If you need a static value from another control at runtime, simply set that value in the page load event or handle it another way in the code behind.


Solution

  • you need to put ' around your text in the saySomething() call.

    Like this:

        <asp:Button runat="server" ID="btnSaySomething1" Text="Say Something" OnClientClick="saySomething('<%=txtToSay.Text%>');"  />
    

    UPDATE

    <%= %> won't work inside an asp.net control. Can you set it from the code-behind?

    I.E

    btnSaySomething1.OnClientClick = "Text to say"