jQuery:计算表中各节的列总数

时间:2011-02-02 20:59:21

标签: jquery

我有下表:

<table class="stripeMe" cellpadding="0" cellspacing="0" width="100%">
<tbody>
    <tr>
        <th>
            MEALS
        </th>
        <th style="text-align: center;">
            02/6
        </th>
        <th style="text-align: center;">
            02/7
        </th>
        <th style="text-align: center;">
            02/8
        </th>
        <th style="text-align: center;">
            02/9
        </th>
        <th style="text-align: center;">
            02/10
        </th>
        <th style="text-align: center;">
            02/11
        </th>
        <th style="text-align: center;">
            02/12
        </th>
        <th style="text-align: center;">
            Total
        </th>
    </tr>
    <tr>
        <td>
            CONGREGATE - HEALTHY BALANCE
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/6/2011"
            name="116|2/6/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/7/2011"
            name="116|2/7/2011" value="18" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/8/2011"
            name="116|2/8/2011" value="33" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/9/2011"
            name="116|2/9/2011" value="20" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/10/2011"
            name="116|2/10/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/11/2011"
            name="116|2/11/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="116|2/12/2011"
            name="116|2/12/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" readonly="readonly" size="3" class="total"
            id="116|Total" name="116|Total" value="71" />
        </td>
    </tr>
    <tr style="background: #79a2cb;">
        <td>
            <strong>Totals</strong>
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/6/2011"
            name="MEALS|2/6/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/7/2011"
            name="MEALS|2/7/2011" value="18" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/8/2011"
            name="MEALS|2/8/2011" value="33" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/9/2011"
            name="MEALS|2/9/2011" value="20" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/10/2011"
            name="MEALS|2/10/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/11/2011"
            name="MEALS|2/11/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="MEALS|2/12/2011"
            name="MEALS|2/12/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" readonly="readonly" size="3" class="total"
            id="MEALS|Total" name="MEALS|Total" value="71" />
        </td>
    </tr>
    <tr>
        <th>
            BEVERAGES
        </th>
        <th style="text-align: center;">
            02/6
        </th>
        <th style="text-align: center;">
            02/7
        </th>
        <th style="text-align: center;">
            02/8
        </th>
        <th style="text-align: center;">
            02/9
        </th>
        <th style="text-align: center;">
            02/10
        </th>
        <th style="text-align: center;">
            02/11
        </th>
        <th style="text-align: center;">
            02/12
        </th>
        <th style="text-align: center;">
            Total
        </th>
    </tr>
    <tr>
        <td>
            SKIM MILK
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/6/2011"
            name="67|2/6/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/7/2011"
            name="67|2/7/2011" value="4" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/8/2011"
            name="67|2/8/2011" value="10" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/9/2011"
            name="67|2/9/2011" value="5" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/10/2011"
            name="67|2/10/2011" value="10" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/11/2011"
            name="67|2/11/2011" value="4" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="sum" id="67|2/12/2011"
            name="67|2/12/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" readonly="readonly" size="3" class="total"
            id="67|Total" name="67|Total" value="33" />
        </td>
    </tr>

    <tr style="background: #79a2cb;">
        <td>
            <strong>Totals</strong>
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/6/2011"
            name="BEVERAGES|2/6/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/7/2011"
            name="BEVERAGES|2/7/2011" value="4" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/8/2011"
            name="BEVERAGES|2/8/2011" value="10" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/9/2011"
            name="BEVERAGES|2/9/2011" value="5" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/10/2011"
            name="BEVERAGES|2/10/2011" value="10" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/11/2011"
            name="BEVERAGES|2/11/2011" value="4" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" size="3" class="totalCategory" id="BEVERAGES|2/12/2011"
            name="BEVERAGES|2/12/2011" value="0" />
        </td>
        <td style="text-align: center;">
            <input type="text" style="text-align: center;" readonly="readonly" size="3" class="total"
            id="BEVERAGES|Total" name="BEVERAGES|Total" value="33" />
        </td>
    </tr>

</tbody>

我希望能够对每一列求和并将值插入到texbox中。我使用以下jQuery在行级别上为总计工作:

$('input.sum').change(function () {
            var sum = 0;
            $(this).closest('tr').find('input.sum').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                sum += val;
            });
            $(this).closest('tr').find('input.total').val(sum);
        });

列文本框总计的每个类都有一个名称totalCategory。

非常感谢有关如何计算列总数的任何帮助。

======编辑============================

确定。我正在从下面的帮助中解决这个问题。我已将我的javascript更改为以下内容:

$('input.sum').change(function () {
            var sum = 0;
            $(this).closest('tr').find('input.sum').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                sum += val;
            });
            $(this).closest('tr').find('input.total').val(sum);

            var tableID = $(this).closest('tr').parents('table').attr('id');
            var columnIndex = $(this).closest('td').attr("cellIndex");
            sumOfColumns(tableID, columnIndex, true);

        });

我还添加了一个新功能:

 function sumOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;
        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
          .children("td:nth-child(" + columnIndex + ") input.sum")
          .each(function () {
              tot += parseInt($(this).val());
          });
          alert(tot);
    }

现在的问题是我没有从函数sumOfColumns中获取正确的值。我错过了代码吗?

感谢您的帮助。

==解======

以下是我提出的解决方案:

 function sumOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;
        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
          .children("td:nth-child(" + (columnIndex + 1) + ")").find('input.sum')
          .each(function () {
              var val = parseInt($(this).val(), 10);
              if (isNaN(val) || val === undefined) {
                  val = 0;
                  $(this).val(0);
              }
              tot += parseInt(val);
          });

          $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : "")).children("td:nth-child(" + (columnIndex + 1) + ")").find('input.totalCategory').val(tot);
    }


    $(document).ready(function () {
        $('input.sum').change(function () {
            //Initialize variable to hold the totals
            var sum = 0;
            var grandTotal = 0;

            //Sum the row numbers
            $(this).closest('tr').find('input.sum').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                sum += val;
            });

            //Assign the row total to the textbox
            $(this).closest('tr').find('input.total').val(sum);

            //Calculate column totals
            var tableID = $(this).closest('tr').parents('table').attr('id');
            var columnIndex = $(this).closest('td').attr("cellIndex");
            sumOfColumns(tableID, columnIndex, true);

            //Calculate grand totals for the last row
            $("#" + tableID + " tr:last").find('input.totalCategory').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                grandTotal += val;
            });

            $("#" + tableID + " tr:last").find('input.grandTotal').val(grandTotal);



        });
    });

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

这是我的解决方案。它不漂亮,但它有效。

 function sumOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;
        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
          .children("td:nth-child(" + (columnIndex + 1) + ")").find('input.sum')
          .each(function () {
              var val = parseInt($(this).val(), 10);
              if (isNaN(val) || val === undefined) {
                  val = 0;
                  $(this).val(0);
              }
              tot += parseInt(val);
          });

          $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : "")).children("td:nth-child(" + (columnIndex + 1) + ")").find('input.totalCategory').val(tot);
    }


    $(document).ready(function () {
        $('input.sum').change(function () {
            //Initialize variable to hold the totals
            var sum = 0;
            var grandTotal = 0;

            //Sum the row numbers
            $(this).closest('tr').find('input.sum').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                sum += val;
            });

            //Assign the row total to the textbox
            $(this).closest('tr').find('input.total').val(sum);

            //Calculate column totals
            var tableID = $(this).closest('tr').parents('table').attr('id');
            var columnIndex = $(this).closest('td').attr("cellIndex");
            sumOfColumns(tableID, columnIndex, true);

            //Calculate grand totals for the last row
            $("#" + tableID + " tr:last").find('input.totalCategory').each(function (i) {
                var val = parseInt($(this).val(), 10);
                if (isNaN(val) || val === undefined) {
                    return;
                }
                grandTotal += val;
            });

            $("#" + tableID + " tr:last").find('input.grandTotal').val(grandTotal);



        });
    });

答案 1 :(得分:0)

 $('input.sum').change(function () {
        var sum = 0;

        var tr = $(this).closest('tr');
        $('td', tr).not('.totalCategory').each(function(){
        var temp = $(this).find('input.sum').val();
            var val = parseInt(temp, 10);
            if (isNaN(val) || val === undefined) {
                return;
            }
            sum += val;
       });
       $(this).closest('tr').find('input.total').val(sum);
    });

答案 2 :(得分:0)

您可以尝试这样的操作(基于您的确切HTML,并为总计添加额外的行):

$('tr:last').find('input').each(function() { // get "total row" inputs 
    var pos = $(this).closest('td').prevAll().length; // get current column
    var tot = 0;
    var that = this; // reference to last row total field
    var temp = $(this).closest('tr').prevAll() // In all rows above,
      .find('td:eq(' + pos + ')') // find the same-indexed cell
      .find('input').each(function() { // and the input within
        tot += +$(this).val(); // add to total, ensuring number with unary operator
        $(that).val(tot); // final answer
    });
});

您可以通过将类似上述内容放入函数中并将该函数附加到您要编辑的字段的change事件中来动态更新这些总计。

以下是一个有效的例子:http://jsfiddle.net/redler/J2e7v/1/

答案 3 :(得分:0)

另一种选择是遍历表并首先构建列集合,然后在编辑时引用这些集合(这只是一个粗略的想法):

var temp = $('.stripeMe').find('td:first-child').next(); // get the first column
var tempInputs = temp.find('input.sum'); // get the inputs in the first column

while (temp.length > 0 && tempInputs.length > 0) {
    // save the column inputs as "data" attached to each input.
    tempInputs.each(function () { $(this).data("column", tempInputs); });

    temp = temp.next(); // move to next column
    tempInputs = temp.find('input.sum'); // get the inputs for the next column
}

$('input.sum').change(function () {
    var sum = 0;

    // now just add up the values in the column inputs.
    $(this).data("column").each(function () {
        sum += parseInt($(this).val());
    });
    alert(sum);
});