<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientSideSum.aspx.cs" Inherits="ClientSideSum" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> </tr> <td> First Number </td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> <tr> <td> Second Number</td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td> </tr> <tr> <td> Third Number</td> <td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td> </tr> <tr> <td> Fourth Number</td> <td> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox></td> </tr> <tr> <td> Totial #</td> <td> <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox></td> </tr> </table> </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class ClientSideSum : System.Web.UI.Page { private void RegisterTotalScript() { ClientScript.RegisterArrayDeclaration("textBoxIDs", "'" + TextBox1.ClientID + "'"); ClientScript.RegisterArrayDeclaration("textBoxIDs", "'" + TextBox2.ClientID + "'"); ClientScript.RegisterArrayDeclaration("textBoxIDs", "'" + TextBox3.ClientID + "'"); ClientScript.RegisterArrayDeclaration("textBoxIDs", "'" + TextBox4.ClientID + "'"); string script = @" function CalculateTotal(totalTextBoxID) { var runningTotal = 0; for (index = 0; index < textBoxIDs.length; index++) { var value = parseFloat(document.getElementById(textBoxIDs[index]).value); if (!isNaN(value)) runningTotal += value; } document.getElementById(totalTextBoxID).value = runningTotal; }"; if (!ClientScript.IsClientScriptBlockRegistered("totalScript")) ClientScript.RegisterClientScriptBlock(typeof(string), "totalScript", script, true); TextBox1.Attributes.Add("onchange", "CalculateTotal('" + TextBox5.ClientID + "');"); TextBox2.Attributes.Add("onchange", "CalculateTotal('" + TextBox5.ClientID + "');"); TextBox3.Attributes.Add("onchange", "CalculateTotal('" + TextBox5.ClientID + "');"); TextBox4.Attributes.Add("onchange", "CalculateTotal('" + TextBox5.ClientID + "');"); } protected void Page_Load(object sender, EventArgs e) { RegisterTotalScript(); } }


No comments:
Post a Comment