DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

calling Javascript validation function before button click event in ASP.NET - onclientclick before onclick

By Ashok Nalam on 13 Dec 2012 | Category: ASP.NET | Tagged: button javascript onclientclick onclick C# 
In this snippet we will see how to call a java script client side validation function before server side method execution.
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction

In this snippet we will see how to call a java script client side validation function before server side method execution.

Below code shows calling a onClientClick method before onClick methods of button. The methods, onClientClick is calling a client side validation function where as onClick is calling server side code. In the validation function we are checking whether the textbox  value is empty or not. If the value is empty then it returns false and will not execute any server side code. If the textbox has value then it returns true and server side event(btnSubmit_Click) will be executed.

DesignerPage(.aspx)

<head>
    <script type="text/javascript">
        function validate() {
            //if validation sucess return true otherwise return false.
            if (document.getElementById("txtSample").value != "") {
                return true;
            }
            alert('Enter a value');
            return false;
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        Enter a value:<asp:TextBox ID="txtSample" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Click Me" OnClientClick="javascript:return validate();"
            OnClick="btnSubmit_Click" />
    </div>
    </form>
</body>
</html>

CodeBehind(.aspx.cs)

protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("The textbox value is " + txtSample.Text);
}

Output:

If textbox value is empty then validation returns false then alert('Enter a value') comes and server side code will not be executed.
If textbox has value(DotNetMirror) then validation function returns true and server side code executes. and output is "The textbox value is DotNetMirror".

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8586  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.