I am using jQuery and ASP.NET MVC 3 with the razor view engine.
I have a couple of textboxes in which numeric values can be typed. I have a label control that has the totals of the textboxes calculated by jQuery.
I have the following textboxes and label (for the calculated results):
<input id="GrossMonthlySalary" type="text" />
<input id="SpouseGrossMonthlySalary" type="text" />
<input id="AdditionalIncome" type="text" />
<input id="ChildSupportIncome" type="text" />
<label id="TotalMonthlyIncome" class="total-amount"></label>
In my .js file I have the following:
$(function () {
$('#GrossMonthlySalary, #SpouseGrossMonthlySalary, #AdditionalIncome, #ChildSupportIncome').keyup(function () {
var val1 = $('#GrossMonthlySalary').val();
var val2 = $('#SpouseGrossMonthlySalary').val();
var val3 = $('#AdditionalIncome').val();
var val4 = $('#ChildSupportIncome').val();
var totalMonthlyIncome =
(parseInt(val1, 10) || 0) +
(parseInt(val2, 10) || 0) +
(parseInt(val3, 10) || 0) +
(parseInt(val4, 10) || 0);
if (totalMonthlyIncome == 0) {
$('#TotalMonthlyIncome').text('');
}
else {
$('#TotalMonthlyIncome').text(totalMonthlyIncome);
}
});
});
If I click on my submit button and there are errors then the errors are displayed and the my label control with the calculated results are cleared. How do I retain the values after post back?
Just another question on the way that I calculated the results, is this good or is there a better way?
Keep in mind that parseInt will fail the second it hits a non numeric character:
As far as calculating the total, since you aren’t doing any additional processing for specific values, you could simplify the whole thing by using a class selector.