Retaining calculated jQuery totals after postback
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 totalMon开发者_开发问答thlyIncome =
(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:
parseInt('$10') // NaN
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.
$('.incomes').keyup(function () {
var incomes = $('.incomes'),
totalDisplay = $('#TotalMonthlyIncome'),
totalVal = 0;
incomes.each(function() {
var matches = null;
// find the number to add to total
matches = $(this).val().match(/\d+/);
// not bothering with the regex on totalVal because we set it
totalVal = ( matches !== null ? parseInt(matches[0],10) : 0 ) + parseInt(totalVal,10);
});
totalVal = totalVal === 0 ? '' : totalVal;
totalDisplay.text(totalVal);
});
Your jQuery code looks just fine. I can shorten it a little ( http://jsfiddle.net/JBqRj/4 ), but it doesn't actually optimize anything.
If you want to post it to the server, then you should just need to add a hidden text field to your form containing the same value as your label: http://jsfiddle.net/JBqRj/5/
In order to retain the posted values following the error, though, you need to do that within your ASP code. Just have it fill the form fields (including the hidden field) with the same ones that were posted.
精彩评论