在回发后保留计算的jQuery总数

时间:2011-09-07 12:01:36

标签: javascript jquery asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我将jQueryASP.NET MVC 3razor view engine一起使用。

我有几个文本框,可以输入数值。我有一个标签控件,其中包含由jQuery计算的文本框的总数。

我有以下文本框和标签(对于计算结果):

<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>

在我的.js文件中,我有以下内容:

$(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);
      }
   });
});

如果单击我的提交按钮并且出现错误,则会显示错误,并清除带有计算结果的标签控件。如何在回发后保留这些值?

关于我计算结果的方式的另一个问题,这是好还是有更好的方法?

2 个答案:

答案 0 :(得分:1)

你的jQuery代码看起来很好。我可以稍微缩短它(http://jsfiddle.net/JBqRj/4),但它实际上并没有优化任何东西。

如果您想将其发布到服务器,则只需在表单中添加隐藏文本字段,其中包含与您的标签相同的值:http://jsfiddle.net/JBqRj/5/

但是,为了保留错误后的发布值,您需要在ASP代码中执行此操作。只需填写表单字段(包括隐藏字段)和发布的相同字段。

答案 1 :(得分:1)

请记住,parseInt会在第二次命中非数字字符时失败:

parseInt('$10') // NaN

就计算总数而言,由于您没有对特定值进行任何额外处理,因此可以使用类选择器简化整个过程。

$('.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);
});