jQuery根据相关复选框选择求和单元格


jQuery sum cells based on related checkbox selection

我有一张发票编号、日期和到期总额的表格。我希望所选的总数在一个变量中返回给jQuery。PHP目前正在生成该表,所以如果它有助于向输入添加唯一的ID或修改HTML输出,那根本不是问题。

我对此做了一些研究,似乎有一百万种方法可以实现我想要的;从在输入中连接ID和Prices('5:75.97'样式),然后将它们分开进行操作,一直到在HTML中搜索最近的复选框并以这种方式添加数字。它们看起来都会起作用;只是好奇地想知道理想的解决方案是什么。

例如,如果选择了发票5和12,则变量将等于106.94

如有任何帮助,我们将不胜感激。

<table>
    <tr>
        <th>Invoice #</th>
        <th>Date</th>
        <th>Balance</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 5  </td>
        <td>2015-03-03</td>
        <td>75.97</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 8</td>
        <td>2015-03-07</td>
        <td>35.97</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 12</td>
        <td>2015-03-01</td>
        <td>30.97</td>
    </tr>
</table>

以下是我的操作方法:

    var totalInvoice;
    $('input').on('change', function(){
        totalInvoice = 0;
        $('input:checked').each(function(){
            totalInvoice += parseFloat($(this).parent().siblings('td:nth-last-child(1)').text());
        });
        console.log(totalInvoice);
    })

请记住,最好指定类或其他类引用的输入。

我建议:

// finding the inputs of type=checkbox, binding a change 
// event-handler:
$('table input[type="checkbox"]').on('change', function() {
  // finding the closest <table>:
  var table = $(this).closest('table'),
    // finding the checked checkboxes inside of that <table>:
    checked = table.find('input[type=checkbox]:checked'),
    // getting the last <td> from the <tr> that contains the
    // checked checkboxes:
    prices = checked.closest('tr').find('td:last-child'),
    // iterating over those <td> elements:
    sum = prices.map(function() {
      // creating a map containing the found prices, if the
      // trimmed text is not a number we return 0:
      return parseFloat(this.textContent.trim(), 10) || 0;
    // converting the map to an array, and passing it
    // to the reduce method:
    }).get().reduce(function(a, b) {
      // summing the current value (a) with new value (b):
      return a + b;
    });
  // setting the text of the element whose id="result":
  $('#result').text(sum);
// triggering the change event (in the case of any
// checkboxes being checked on page-load:
}).change();

$('table input[type="checkbox"]').on('change', function() {
  var table = $(this).closest('table'),
    checked = table.find('input[type=checkbox]:checked'),
    prices = checked.closest('tr').find('td:last-child'),
    sum = prices.map(function() {
      return parseFloat(this.textContent.trim(), 10) || 0;
    }).get().reduce(function(a, b) {
      return a + b;
    });
  $('#result').text(sum);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th>Invoice #</th>
      <th>Date</th>
      <th>Balance</th>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="Invoices[]" value="" />Invoice 5</td>
      <td>2015-03-03</td>
      <td>75.97</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="Invoices[]" value="" />Invoice 8</td>
      <td>2015-03-07</td>
      <td>35.97</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="Invoices[]" value="" />Invoice 12</td>
      <td>2015-03-01</td>
      <td>30.97</td>
    </tr>
  </tbody>
</table>
<div id="result"></div>

参考文献:

  • CSS:
    • 属性值等于([attribute=value])选择器
    • CCD_ 2
    • :last-child
  • JavaScript:
    • Array.prototype.reduce()
  • jQuery:
    • change()
    • closest()
    • find()
    • get()
    • map()

你可以这样做:小提琴

var sum = 0;
$('input').click(function () {
    if ($(this).is(':checked')) {
        var price = $('.price');
        var add = ($(this).closest('tr').find(price).html());
        add = parseFloat(add).toFixed(2);
        sum += +add;
        console.log(sum);
    } else if (!$(this).is(':checked')) {
        var price = $('.price');
        var add = ($(this).closest('tr').find(price).html());
        add = parseFloat(add).toFixed(2);
        sum -= +add;
        console.log(sum);
    }
});