Controlling Button Execution Through JavaScript Function

Introduction

 
This article is basically a continuation of my previous article of ing a value from a JavaScript function to an ASP.NET function, if you haven't read it then kindly go to it at the following link: 
 
 
In the above example, we have made use of a hidden field to a value from a JavaScript function to an ASP.Net function so that we can validate the age of an employee by storing the value in the hidden field using the JavaScript function and then validating the age in the ASP.NET function by getting the value. The same technique can be done simply through JavaScript. But here we are not concerned with the value to be retrieved on the server side.
 
That means that on the button click event a JavaScript function would be called and it will validate whether the age is >= 18 then only the record would be stored in the database and displayed on the gridview or else an error message should be returned to the user stating that your age is invalid.
 
For doing this we need a SQL table and some procedures; here are those queries:
  1. That means that on the button click event a JavaScript function would be called and it will validate whether the age is >= 18 then only the record would be stored in the database and displayed on the gridview or else an error message should be returned to the user stating that your age is invalid.    
  2.      
  3. For doing this we need a SQL table and some procedures; here are those queries:    
  4.      
  5. create table Employee    
  6.  (    
  7.      Empid int identity(1,1)not null,    
  8.      EName varchar(30)not null,    
  9.      EAge int not null,    
  10.      ESalary int not null,    
  11.      constraint pkeid primary key(Empid)    
  12.  )     
  13.  select * from Employee     
  14.  create procedure prcAddEmp    
  15.  (    
  16.      @name varchar(30),    
  17.      @age int,    
  18.      @salary int    
  19.  )    
  20.  as    
  21.  begin    
  22.  insert into Employee    
  23.  values(@name,@age,@salary)    
  24.  end     
  25.  create procedure prcDisplayRecords    
  26.  as    
  27.  begin    
  28.  select * from Employee    
  29.  end   
The following is the front-end structure:

front-end-structure.gif

The following is the source code for it:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>     
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head id="Head1" runat="server">    
  5.     <title>Untitled Page</title>     
  6.     <script type="text/javascript">    
  7.         function validateAge()    
  8.         {    
  9.             var age=document.forms[0]["txtAge"].value;    
  10.             if(age>=18)    
  11.                 return true;    
  12.             else    
  13.             {    
  14.                 alert("Invalid Age");    
  15.                 return false;    
  16.             }    
  17.         }    
  18.     </script>     
  19. </head>    
  20. <body>    
  21.     <form id="form1" runat="server">    
  22.         <div>    
  23.             <table>    
  24.                 <tr>    
  25.                     <td>Name:    
  26.                     </td>    
  27.                     <td>    
  28.                         <asp:TextBox ID="txtName" runat="server"></asp:TextBox>    
  29.                     </td>    
  30.                 </tr>    
  31.                 <tr>    
  32.                     <td>Age:    
  33.                     </td>    
  34.                     <td>    
  35.                         <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>    
  36.                     </td>    
  37.                 </tr>    
  38.                 <tr>    
  39.                     <td>Salary:    
  40.                     </td>    
  41.                     <td>    
  42.                         <asp:TextBox ID="txtSal" runat="server"></asp:TextBox>    
  43.                     </td>    
  44.                 </tr>    
  45.                 <tr>    
  46.                     <td colspan="2" align="right">    
  47.                         <asp:Button ID="btnSave" OnClientClick="javascript:return validateAge()" runat="server" Text="Save" OnClick="btnSave_Click" />    
  48.                     </td>    
  49.                 </tr>    
  50.             </table>    
  51.             <br />    
  52.             <asp:GridView ID="gvwData" runat="server">    
  53.             </asp:GridView>    
  54.         </div>    
  55.     </form>    
  56. </body>    
  57. </html>   
    The following is the code behind for it:
    1. using System;    
    2.  using System.Configuration;    
    3.  using System.Data;    
    4.  using System.Linq;    
    5.  using System.Web;    
    6.  using System.Web.Security;    
    7.  using System.Web.UI;    
    8.  using System.Web.UI.HtmlControls;    
    9.  using System.Web.UI.WebControls;    
    10.  using System.Web.UI.WebControls.WebParts;    
    11.  using System.Xml.Linq;    
    12.  using System.Data.SqlClient;     
    13.      
    14.  public partial class _Default : System.Web.UI.Page    
    15.  {    
    16.      SqlConnection con;    
    17.      SqlCommand cmd;    
    18.      DataSet ds;    
    19.      string dbcon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;     
    20.      protected void Page_Load(object sender, EventArgs e)    
    21.      {     
    22.      }    
    23.      protected void btnSave_Click(object sender, EventArgs e)    
    24.      {    
    25.          string msg = "";    
    26.          con = new SqlConnection(dbcon);    
    27.          cmd = new SqlCommand("prcAddEmp", con);    
    28.          cmd.CommandType = CommandType.StoredProcedure;    
    29.          cmd.Parameters.AddWithValue("@name", txtName.Text);    
    30.          cmd.Parameters.AddWithValue("@age", txtAge.Text);    
    31.          cmd.Parameters.AddWithValue("@salary ", txtSal.Text);    
    32.          con.Open();    
    33.          int rows = cmd.ExecuteNonQuery();    
    34.          if (rows > 0)    
    35.              msg = "<script>alert('Record Saved Successfully')</script>";    
    36.          else    
    37.              msg = "<script>alert('Error Saving Record')</script>";    
    38.          ClientScript.RegisterClientScriptBlock(this.GetType(), "Message", msg);    
    39.          con.close();    
    40.      }    
    41.  } 
      Here is the output for it:
       
      If the age entered is >= 18 then the following output is generated:

      validaion-through-javascript.gif

      validaion-through-javascript1.gif

      Or else if the age < 18:

      validaion-through-javascript2.gif

      The concept is quite clear; over here what we did is, in the Button declaration we added an onClientClick event which is basically a JavaScript function which returns either true (if the age value is >= 18) or else false.
      1. <asp:Button ID="btnSave" OnClientClick="javascript:return validateAge()" runat="server" Text="Save" OnClick="btnSave_Click" />   
      The default behavior of the button is to do a postback whenever the button is clicked, but since the JavaScript function is returning true or false, whenever the JavaScript function returns false, the button's server-side code (ie Button_Click) event is not called because it stops the execution there itself.
       
      Hope you have liked the article.