Craig
Craig

Reputation: 18684

Calculate the total of values in text boxes

I have a screen on my ASP.Net page, which, depending on a selection by the user, they get offered between 1 and 5 text boxes. These boxes allow the user to type in an amount.

When the user enters the screen, based on certain criteria, a certain number of these edit boxes are displayed. They are not hidden... if I want 3 boxes, then only 3 boxes are on the screen.

In javascript, as the user types in an amount, a 'Total' edit box is displayed, summing up the values from each box.

So, as the user types, the value in the total updates with the total calculated for all text boxes:

I use:

onkeyup="calculateTotal()"

on the editbox.

To do that, I use the code below:

function calculateTotal() {

        var amt0 = $('.txtAmount0').val();
        var amt1 = $('.txtAmount1').val();
        var amt2 = $('.txtAmount2').val();
        var amt3 = $('.txtAmount3').val();
        var amt4 = $('.txtAmount4').val();


        var amt = Number(amt0);
        if (!isNaN(amt1))
            amt += Number(amt1);

        if (!isNaN(amt2))
            amt += Number(amt2);

        if (!isNaN(amt3))
            amt += Number(amt3);

        if (!isNaN(amt4))
            amt += Number(amt4);

        $('.txtTotalAmount').text('$' + amt);

    }

The first issue is that it seems I am losing some precision in the calculation:

enter image description here

I am not sure why I am getting a strange rounding issue, when all I am doing is summing up.

Additionally, it seems a bit dirty, if I added more boxes, I need to modify the code.

Is there a better way for this code to work?

Upvotes: 0

Views: 74

Answers (1)

codebased
codebased

Reputation: 7073

You can something like this:

  var sum = 0;
  $("input[class*='txtAmount']").each(function() {
           if ($.isNumeric($(this).val()) ) {
        sum += Number($(this).val());
        }
    });

   $('.txtTotalAmount').text('$' + sum.toFixed(2));

Upvotes: 1

Related Questions