1

I have a jquery script on a page that's coming together, thanks to code and people here, and i'm stuck at a point where I need to call a part of a larger function. I'm not sure how to break into multiple functions i think. Everything runs correctly when i create dynamic input fields and it totals up some amount fields into a totals box, but if i don't create new input boxes then it don't get that part i need to total up these inputs. Here is a sample of what i have so far with a comment in the code where i need help:

http://jsfiddle.net/A3dnr/

// ** Need help to call just this part when text is entered/changed in any of the 'amount' fields **
   var total = 0;
    $('input[name^="Amount"]').each(function () {
        total += parseInt(this.value, 10) || 0;
        if (this.value.length === 0) this.value = 0;
    });
    $('#Totals').val(total);
4

3 回答 3

1

计算总数的代码块位于添加新行按钮的单击处理程序中,因此只有在按下此按钮时才会调用它。您需要将其移到点击处理程序之外。检查这个小提琴。我已将其转换为如下函数

        function updateTheTotal(){
           var total = 0;
           $('input.Amount').each(function () {
              total += parseInt(this.value, 10) || 0;
              if (this.value.length === 0) this.value = 0;
           });
           $('#Totals').val(total);
        }

它会在所有金额字段 的keyup上被调用

$('.Amount').on('keyup', updateTheTotal);

注意:您的代码是通过缓存选择器进行优化的候选者

于 2013-04-19T21:43:05.430 回答
0

您需要添加一个事件。首先在每个金额输入上添加一个“金额”类。然后添加如下内容:

$('table').on('change', '.amount', function() {
  var amount = 0;
  $('.amount').each(function() {
    amount =+ this.value;
  })
  $('#Totals').val(amount);
})

此外,还将 type="number" 添加到您的金额输入中。

于 2013-04-19T21:42:47.533 回答
0

创建一个函数来执行总计,并在现有的单击事件和绑定到字段更改的新更改事件中调用它。

function updateTotal()
{
    var total = 0;
    $('input[name^="Amount"]').change(function () {
        total += parseInt(this.value, 10) || 0;
        if (this.value.length === 0) this.value = 0;
    });
    $('#Totals').val(total);        
}

$('body').on('change','input[name^="Amount"]',function () {
    updateTotal();
});
于 2013-04-19T21:43:53.677 回答