如何使用jquery获取表的所有文本框的总和?

时间:2016-07-20 08:57:01

标签: jquery textbox datatables

我有一个有7列的数据表。最后一列有文本框,用户可以在其中输入付款金额。以下是相同的HTML代码:

<table id="multiple-account-table" cellpadding="0" cellspacing="0">
    <thead>
        <tr class="border-class">
            <th>Employee Name</th>
            <th>Account Number</th>
            <th>Account Name</th>
            <th>Alias</th>
            <th>Due Date</th>
            <th>Total Due</th>
            <th>Payment Amount</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                 <th></th>
                <th></th>
                 <th id="payment-footer"></th>
             </tr>
          </tfoot> 
</table>

使用jquery的数据表方法动态生成表的行。

以下是最后一栏中文本框的HTML代码:

<input type="number" id="payement-textbox" class="payment" step="any" maxlength="9" value="" name="payment-textbox" placeholder="--"/>

我的要求是,当用户在任何文本框中输入金额时,文本框的总和应该同时更新。所有文本框中的付款金额总和显示在表格页脚中。用户不必在所有文本框中输入金额。因此,将显示用户输入任何值的所有行的总和。

我编写的jQuery代码工作正常。唯一的问题是,如果用户减少文本框中的值,那么总和不会相应减少。例如,假设用户在第一个文本框中输入了50,在第二个文本框中输入了100,那么sum将显示在&#34; 150&#34;这是正确的。

但是如果用户将第二个文本框的值更改为50,那么它们的总和将显示在&#34; 150&#34;而不是&#34; 100&#34;。

以下是我的jquery代码:

$(document).on("blur paste",'input.payment', function(event) {
  //taking value of sum which is initially zero

    var temp = $("#payment-footer").html(); 
    var sum = parseFloat(temp);
    if( $(this).val() != ""){
    var sum = sum + parseFloat($(this).val());
     $("#payment-footer").html('$'+sum); 
  }
});

1 个答案:

答案 0 :(得分:0)

迭代循环遍历数据表的所有文本框并对其进行求和。

$(document).on("blur paste",'#multiple-account-table input.payment', function(event) {  
      var sum = 0;
      //Loop through all the textboxes of datatable and make sum of the values of it.
      $.each('#multiple-account-table input.payment',function(){
        var sum = sum + parseFloat($(this).val());
      });
      //Replace the latest sum.
      $("#payment-footer").html(sum); 
    });
相关问题