1

How to call javascript function and code behind function using button?

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return javascriptfunction();" runat="server">

</asp:button>

I tried like this too. but no response.

<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return true;" runat="server">

</asp:button>

even, javascript function return true, its not calling codebehind function. May i know reason?

Tim
  • 1,755
  • 2
  • 22
  • 34
mayil
  • 11
  • 1
  • 1
  • 3
  • Are you using C# or VB? Also, you also need to expand upon what you are trying to accomplish. Are you trying to just simply call both regardless? Are you trying to call the JS method and only call the CodeBehind method if the JS method returns true? Etc. – Code Maverick Mar 28 '13 at 22:00
  • Look at : http://stackoverflow.com/questions/2155048/onclientclick-and-onclick-is-not-working-at-the-same-time – Sinan AKYAZICI Mar 28 '13 at 22:11

2 Answers2

3

The code should be something like this -

JavaScript:

<script>
    function save() 
    {
        return confirm('Are you sure you want to continue?');            
    }
</script>

ASPX:

<asp:Button ID="btnSave" OnClick="btnSave_Click" OnClientClick="return save();" 
   runat="server" />

C# CodeBehind:

protected void btnSave_Click(object sender, EventArgs e)
{
   // Do something
}

It basically call JavaScript function before posting back to server. Whether post back to server or not is depending upon the return value from JavaScript function.

Button control's OnClick is an server side event so you need to attach to server side click event.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
Win
  • 61,100
  • 13
  • 102
  • 181
0

The best way I have found to do this is from code behind using RegisterStartupScript

 ScriptManager.RegisterStartupScript(this, this.GetType(), "name", "javascriptfunction();", true);
Vortex
  • 663
  • 6
  • 7