0

I have a asp.net button

I want to run a JavaScript function animation() along with the asp.net function Button1_Click when the user clicks on submit.

i have written the following code for the same but unable to get the desired result

protected void Button1_Click(object sender, EventArgs e)
    {
        Button1.Attributes.Add("onClick", "animation()");
    <Some Code Here>
     }
5
  • Not sure if it matters but it should be lowercase letters on the attribute key. Commented Feb 28, 2014 at 11:58
  • try it bysetting onclientclick attribute Commented Feb 28, 2014 at 12:01
  • Use OnClientClick to have your ASP.NET button run a JavaScript method before calling its server-side method. OnClick specifies the server side method to run. Commented Feb 28, 2014 at 12:04
  • "onclientclick" is not working, gives an error "Cannot find function" Commented Feb 28, 2014 at 12:05
  • try using Button1.Attributes.Add("onClick", "javascript:animation()"); Commented Feb 28, 2014 at 12:23

3 Answers 3

1

You must include your code outside of the click definition. you can include it on page_load event as..

 protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
             Button1.Attributes.Add("onclick", "animation()");

        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You may also use a script manager to run your javascript functions from server side:
1) You must add a script manager to your page
eg: <asp:ScriptManager ID="scriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="true" AsyncPostBackTimeout="600" />

2) on your _Click function protected void Button1_Click(object sender, EventArgs e) { string script = "$(function(){animation();});"; ScriptManager.RegisterStartupScript(this, this.Page.GetType(), Guid.NewGuid().ToString(), script, true); }

there are two methods you may use with ScriptManager:
- RegisterStartupScript
- RegisterClientScriptBlock
here is a post that tells the difference between them

Comments

0

You can add the javascript function on OnClientClick attribute of the Button.

like

<asp:Button id="Button1" runat="server" OnClientClick="animation();" OnClick="Button1_Click" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.