mayil
mayil

Reputation: 11

How to call javascript function and code behind using button

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?

Upvotes: 1

Views: 22874

Answers (2)

Win
Win

Reputation: 62260

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.

Upvotes: 3

Vortex
Vortex

Reputation: 653

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

 ScriptManager.RegisterStartupScript(this, this.GetType(), "name", "javascriptfunction();", true);

Upvotes: 0

Related Questions