简体   繁体   English

如何用javascript和jQuery总结几个列?

[英]How do I sum up several columns with javascript and jQuery?

I have a table with two different columns that I would like to add up to their respective sums. 我有一个包含两个不同列的表,我想将它们加到各自的总和中。 Right now I just add up one of the columns, I could add up the second column by just making the same JS again but with different names for the values but that is not so pretty. 现在我只是添加其中一个列,我可以通过再次制作相同的JS来添加第二列,但是值的名称不同但不是那么漂亮。 How would I do to change it so it counts the ue column as well as the egen and spit out two results, sum and sum2 . 我该如何改变它,以便计算ue列和egen,并吐出两个结果, sumsum2

<table>
    <tr>
    <td><asp:TextBox ID="TextBox1" runat="server">Number</asp:TextBox></td>
    <td class="egen"><asp:TextBox ID="TextBox56" runat="server" Columns="1">56</asp:TextBox></td>
    <td class="ue"><asp:TextBox ID="TextBox57" runat="server" Columns="1">57</asp:TextBox></td>
    </tr>
    <tr>
    <td><asp:TextBox ID="TextBox2" runat="server">Worker</asp:TextBox></td>
    <td class="egen"><asp:TextBox ID="TextBox58" runat="server" Columns="1">58</asp:TextBox></td>
    <td class="ue"><asp:TextBox ID="TextBox59" runat="server" Columns="1">59</asp:TextBox></td>
    </tr>
    <tr>
    <td align="right">Sum:</td>
    <td align="center"><span id="sum"></span></td>
    <td align="center"><span id="sum2"></span></td
    </tr>
</table>

This is my javascript that I use to add up the values in the column egen . 这是我用来添加egen列中的值的javascript

$(document).ready(function () {

    //iterate through each td based on class / input and add keyup
    //handler to trigger sum event
    $(".egen :input").each(function () {

        $(this).keyup(function () {
            calculateSum();
        });
    });

});
function calculateSum() {

    var sum = 0;
    // iterate through each td based on class and add the values from the input
    $(".egen :input").each(function () {

        var value = $(this).val();
        // add only if the value is number
        if (!isNaN(value) && value.length != 0) {
            sum += parseFloat(value);
        }
    });
    $('#sum').text(sum);
};

You can target all elements in .egen or .ue by the following selector: 您可以通过以下选择器定位.egen .ue的所有元素:

 $('.egen :input, .ue :input')

Or if you prefer: 或者如果您愿意:

$('.egen, .ue').find(':input')

By the way you don't need to iterate over the collection of elements to bind keyup listeners to them, you can bind to the entire collection immediately: 顺便说一下,您不需要迭代元素集合来将keyup侦听器绑定到它们,您可以立即绑定到整个集合:

$('.egen :input, .ue :input').keyup(calculateSum);

EDIT 编辑

I note from the presence of #sum and #sum2 that you may want to sum up the columns separately. 我注意到#sum#sum2的存在,你可能想要分别总结列。 You could do something like this: 你可以这样做:

$('.egen :input').keyup(function() { calculateSum('.egen'); });
$('.ue :input').keyup(function() { calculateSum('.ue'); });

function calculateSum(container) {
   var sum = 0;
   $(container).find(':input').each(function() {
       ... 
   });
}

And then of course set the value of #sum or #sum2 , respectively. 然后当然分别设置#sum#sum2的值。 That could be acheived in a number of ways. 这可以通过多种方式实现。 Either you pass the id, just as we're passing the class above, or you use a class named sum , and have the respective td 's reuse the egen and ue classes. 要么传递id,就像我们传递上面的类一样,或者你使用一个名为sum的类,并让各自的td重用egenue类。 That way you could access the correct sum with $(container+'.sum').val() . 这样你就可以用$(container+'.sum').val()访问正确的总和。 Another solution would be to just return the sum, and setting it in your keyup listener: 另一个解决方案是返回总和,并在keyup监听器中设置它:

$('.ue :input').keyup(function() {
   $('#sum2').val( calculateSum('.ue') );
});

Note also that your parsing could be simplified. 另请注意,您的解析可以简化。 parseFloat will yield NaN for a lot of invalid values, including empty strings and null , so you do not need to check your values closely before calling it. parseFloat将为许多无效值产生NaN ,包括空字符串和null ,因此在调用之前不需要仔细检查您的值。 NaN will evaluate to false, so you could always sum by (parsedResult || 0) , as the result would be 0 , leaving the sum unaffected, if parsedResult is NaN . NaN将评估为false,因此您总是可以求和(parsedResult || 0) ,因为结果将为0 ,如果parsedResultNaN ,则总和不受影响。

Thus: 从而:

var sum = 0;
$(container).find(':input').each(function() {
   sum += (parseFloat( $(this).val() ) || 0);
});

changed your sum <span> id to its respective class_sum like 将您的总和<span> id更改为其各自的class_sum

<span id="egen_sum"></span>
<span id="ui_sum"></span>
...

so that we can get this working with one function 这样我们就可以使用一个函数

try this 尝试这个

$('.egen :input, .ue :input').keyup(function(){
     var keyupClass= $(this).parent().hasClass('egen') ? 'egen' : 'ue';
     calculateSum(keyupClass);
 });

function calculateSum(keyupClass) {

  var sum = 0;
  $("."+ keyupClass+" :input").each(function () {

    var value = $(this).val();
    // add only if the value is number
    if (!isNaN(value) && value.length != 0) {
        sum += parseFloat(value);
    }
  });
  $('#'+keyupClass+"_sum").text(sum);
};

this will work for any number of input ... just need to make sure the corresponding sum span is given the right id... 这将适用于任何数量的输入...只需确保相应的总和得到正确的id ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM