How do I in javascript/asp add two textbox values and display in third?
My JS code
function sum() {
var txtFirstNumberValue = document.getElementById('TextBox1').value;
var txtSecondNumberValue = document.getElementById('TextBox2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('TextBox3').value = result;
}
}
ASP in page load
TextBox1.Attributes.Add("onkeyup", "sum();");
TextBox2.Attributes.Add("onkeyup", "sum();");
One thing you should know:
By default, ASP.NET uses auto-generated ClientID property to be used by TextBox control in ASPX pages, so that your textbox ID will become something like <input id="ctl00_ContentPlaceHolder1_TextBox1" type="text" ... /> after rendered. To use the server control name in client-side you need to use ClientID like this:
function sum() {
var txtFirstNumberValue = document.getElementById('<%= TextBox1.ClientID %>').value;
var txtSecondNumberValue = document.getElementById('<%= TextBox2.ClientID %>').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('<%= TextBox3.ClientID %>').value = result;
}
}
An alternative to avoid using generated ClientID in client-side is setting ClientIDMode to be static, here are examples to use it:
<%-- control level --%>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ... />
<%-- placeholder level --%>
<asp:Content ID="Content1" runat="server" ClientIDMode="Static" ...>...</asp:Content>
<%-- page level --%>
<%@ Page Language="C#" ClientIDMode="Static" AutoEventWireup="true" ... %>
Reference:
ClientID Property
Set HTML Attributes for Controls in ASP.NET Web Pages
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With