On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 will appear on the screen.
As the user inputs an amount, a 'Total' edit box dynamically updates to show the sum of all values entered in the text boxes. This is achieved using the following JavaScript code triggered by the onkeyup event:
onkeyup="calculateTotal()"
The calculation is carried out by this function:
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);
}
However, there seems to be a precision issue in the calculation and a need to update the code if more boxes are added. Is there a cleaner, more efficient solution for this functionality?