Wednesday, August 29, 2012

How to: Call JavaScript function on OnClientClick event of Asp.Net button

The Asp.Net button is a server control and its click event is by default associated with a server side event handler function as follows.
OnClick="btnSave_Click"
But there are situations where we need to perform client side operations by calling a JavaScript function before submitting the page to the server side event handler, this can be achieved by assigning a JavaScript function to the OnClientClick event of the button as follows.
OnClientClick="JavascriptFunction();

Here is a full example



<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>OnClientClick</title>
    <script language="javascript">
        function JavascriptFunction() {
            alert("Hi! I am a Javascript Function");
        }
    </script>
</head>
<body>
    <form id="frmOnClientClick" runat="server">
    <div>
        <asp:Button
      id="btnSave"
            runat="server"
Text="Save"             
OnClientClick="JavascriptFunction();"/>
    </div>
    </form>
</body>
</html>

Here when the user clicks on the button the client side Javascript function JavascriptFunction() will be called first, following which the server side function btnSave_Click will be executed.

Related Post
Asp.Net Button OnClientClick Example
How to: Call JavaScript function on OnClientClick event of Asp.Net button
Asp.Net Button OnClick Vs OnClientClick
Asp.Net Button OnClientClick prevent post back.
Asp.net button OnClientClick Confirm Message

Search Flipkart Products:
Flipkart.com

No comments: