简体   繁体   中英

sum of 2 asp:textbox values using c# asp.net

how do i simply type a value in 1 box and have it populate in another using the asp:textbox. I simply want to pull value from 1 asp:textbox and put it in another, ultimately i am going to be adding the sum of 2 boxes and placing it in another, I would like this to happen in real time and not use a button.

Use javascript:

<asp:TextBox ID="txtTextSource" runat="server" onblur="TextSource_OnBlur(this)" />
<asp:TextBox ID="txtTextDestination" runat="server" />
<script type="text/javascript">
    function TextSource_OnBlur(oElement) {
        var destination = document.getElementById('<%= txtTextDestination.ClientID %>');
        destination.value = oElement.value;
    }
</script>

Instead of ASP.net, use jQuery for this since it'll avoid post backs.

hook onto the change event of textbox1 and populate text box 2 using jQuery. Try it and let us know.

I agree with raja, you should use client side JavaScript (doesn't have to be jQuery) to handle this since it doesn't require server interaction. But let's say for some crazy reason you want it to happen on the server.

First Number: <asp:TextBox runat="server" id="TB1" /><br />
Second Number: <asp:TextBox runat="server" id="TB2" /><br />
<asp:Button runat="server" id="CalculateBtn" OnClick="CalculateBtn_Click" Text="Calcualte Sum" />
Sum: <asp:TextBox runat="server" id="SumTB" />

Code Behind

protected void CalculateBtn_Click (object sender, EventArgs e)
{
    int num1 = Int32.Parse(TB1.Text);
    int num2 = Int32.Parse(TB2.Text);
    int sum = num1+num2;
    SumTB.Text = sum.ToString();
}

Obviously you can get much more fancy, using doubles instead of ints and verifying that the user typed a valid number and using ScriptMethods or UpdatePanels to do it in real time without the need for a button. But seriously, stick with a client side solution.

          $('.amount-input').live('blur', function () {
                  var amountSum = 0;
                       $('.amount-input').each(function () {
                         amountSum += parseInt($(this).val());
                       });

                           $('#<%= Damount.ClientID %>').val(amountSum);
                 enter code here

just used java script and called the total amount which is "Damount" from the server code. Still wish it changed in real time except for when i click off the textbox but hey it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM