sachin
sachin

Reputation: 1

Automatically calculate value of TextBox

How to get the value of textbox3 automatically by calculating textbox1-textbox2 when textbox1 and textbox2 values entered.

<asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>//enter value as 100
<asp:TextBox ID="txtbox2" runat="server"></asp:TextBox>//enter value as 50, Once we enter 50 result should appear in textbox3

<asp:TextBox ID="txtbox3" runat="server"></asp:TextBox>//Once we enter 50 result should appear in textbox3

txtbox3.Text = (Convert.ToInt32(txtbox1.Text) - Convert.ToInt32(txtbox2.Text)).ToString();

Upvotes: 0

Views: 4973

Answers (3)

Arvin
Arvin

Reputation: 1014

<asp:TextBox ID="txt1" runat="server" onchange='return Calculate();'></asp:TextBox>

<asp:TextBox ID="txt2" runat="server" onchange='return Calculate();'></asp:TextBox>

if you are using javascript------

<script type="text/javascript">
function Calculate(){

document.getElementById('<%=txt3.ClientID%>').value = 
document.getElementById('<%=txt1.ClientID%>').value - document.getElementById('<%=txt2.ClientID%>').value;
}
</script>

now if you are using jquery------

function Calculate(){
$("#<%=txt3.ClientID%>").val() = 
$("#<%=txt1.ClientID%>").val - $("#<%=txt2.ClientID%>").val();
}

please change the IDs with your IDs this will work

Upvotes: 0

tdelepine
tdelepine

Reputation: 2016

If is not necessary to call back the server side for this simple operation. you can try this :

On Text1 and Text2 place onchange Event handler client side.

<asp:TextBox ID="txtbox1" runat="server" onchange='return calculateValueText3();'></asp:TextBox>

<asp:TextBox ID="txtbox2" runat="server" onchange='return calculateValueText3();'></asp:TextBox>

Add a Javascript section

<script>
function calculateValueText3 ()
{
//for example
document.getElementById('<%=txtbox3.ClientID%>').value = 
document.getElementById('<%=txtbox1.ClientID%>').value - document.getElementById('<%=txtbox2.ClientID%>').value
}
</script>

Upvotes: 1

Nickolai Nielsen
Nickolai Nielsen

Reputation: 942

You would need to use the event "TextChanged" on txtbox1 and txtbox2 to do the calculations

Upvotes: 5

Related Questions