jquery 如何使用JavaScript对表中的所有列值求和

vuktfyat  于 2023-06-22  发布在  jQuery
关注(0)|答案(3)|浏览(142)

在我的web应用程序中,我使用JavaScript动态地将表行添加到表中。
每一行都有数量列、单位金额列和行合计列。
在将记录添加到表中之后,用户还可以删除该行。
在此场景中,我希望获取Line Totalcol值的总和,以显示为Total Value
如何使用JavaScript计算?
这是我目前的代码。

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>

这就是如何动态地向表中添加行。

var counter = 1;

var dropdownOptions = @Html.Raw(Json.Encode(ViewBag.Item_ID));

$(function () {
  $("#add").click(function () {
    var newRow = $(
       '<tr id="tablerow' +
       counter +
       '" class ="poSet"> ' +
       "<td>" +
       '<label id="CountItems"><strong>' +
       counter +
       "</strong></label>" +
       "</td>" +
       '<td width="40%">' +
       '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
       counter +
       ']" id="ItemId[' + counter + ']" required="required" ' +
       "</select>" +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control Qty" name="Qty[' +
       counter +
       ']" value="1" id="Qty[' + counter + ']" onchange="calQtyBase(this)" data-QtyId= ' + counter + ' required="required" />' +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control" name="MeasureBy[' +
       counter +
       ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
       counter +
       ']" value="0.00" id="UnitPrice[' + counter + ']"  onchange="priceBase(this)" data-PriceId= ' + counter + '  required="required" />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control LineTotal" name="Line_Total[' +
       counter +
       ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
       "</td>" +
       "<td>" +
       '<button type="button" class="btn btn-danger" onclick="removeTr(' +
       counter +
       ');">x</button>' +
       "</td>" +
       "</tr>"
     );
    
    var selectElement = newRow.find("select"); 

    dropdownOptions.forEach(function (option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    newRow.appendTo("#submissionTable");

    selectElement.select2();

    counter++;
    return false;
  });
});

这里我写了一个2的JavaScript来计算OnChange事件中数量单价发生变化时的行合计

function calQtyBase(e) {

   var dataId = e.getAttribute("data-QtyId");
   var Qty = document.getElementById('Qty[' + dataId + ']').value;
   var UnitAmount = parseFloat(document.getElementById('UnitPrice[' + dataId + ']').value);
   var total = Qty * UnitAmount;
   document.getElementById('LineTotal[' + dataId + ']').value = parseFloat(Math.round(total * 100) / 100).toFixed(2);

 }
function priceBase(e) {
   var dataId = e.getAttribute("data-PriceId");
   var Qty = document.getElementById('Qty[' + dataId + ']').value;
   var UnitAmount = parseFloat(document.getElementById('UnitPrice[' + dataId + ']').value);
   var total = Qty * UnitAmount;
   document.getElementById('LineTotal[' + dataId + ']').value = parseFloat(Math.round(total * 100) / 100).toFixed(2);

 }
qzlgjiam

qzlgjiam1#

您可以循环遍历lineTotal输入框,并使用+=在每次迭代中添加每个输入的值,然后将此值分配给任何div以显示total。
此外,我在你当前的代码中做了一些小的修改,所以不是多个函数,而是添加了更改处理程序,它将调用数量和价格更改,并在该处理程序中调用calculate_total函数来更新总数。

演示代码:

var counter = 1;

var dropdownOptions = [{
  "Value": "test",
  "Text": "tyty"
}];

$(function() {
  $("#add").click(function() {
    var newRow = $(
      '<tr id="tablerow' +
      counter +
      '" class ="poSet"> ' +
      "<td>" +
      '<label id="CountItems"><strong>' +
      counter +
      "</strong></label>" +
      "</td>" +
      '<td width="40%">' +
      '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
      counter +
      ']" id="ItemId[' + counter + ']" required="required" ' +
      "</select>" +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control Qty" name="Qty[' +
      counter +
      ']" value="1" id="Qty[' + counter + ']" data-QtyId= ' + counter + ' required="required" />' +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control" name="MeasureBy[' +
      counter +
      ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
      counter +
      ']" value="0.00" id="UnitPrice[' + counter + ']"  data-PriceId= ' + counter + '  required="required" />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control LineTotal" name="Line_Total[' +
      counter +
      ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
      "</td>" +
      "<td>" +
      '<button type="button" class="btn btn-danger" onclick="removeTr(' +
      counter +
      ');">x</button>' +
      "</td>" +
      "</tr>"
    );

    var selectElement = newRow.find("select");

    dropdownOptions.forEach(function(option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    newRow.appendTo("#submissionTable");

    selectElement.select2();

    counter++;
    return false;
  });
});

//onchange of qty & unitprice
$(document).on("change", ".Qty , .UnitPrice ", function() {
  var element = $(this).closest("tr");
  var qty = element.find(".Qty").val();
  var unit_price = element.find(".UnitPrice").val();
  var total = qty * unit_price;
  element.find(".LineTotal").val(parseFloat(Math.round(total * 100) / 100).toFixed(2));

  calculate_total(); //call function

})

function calculate_total() {
  var sum = 0;
  //looping
  $('[id*=LineTotal]').each(function(el) {
    sum += parseFloat($(this).val()) // adding values
  })
  $("#total").text(sum.toFixed(2)) //added in total div..

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  Total :
  <div id="total"></div>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>
byqmnocz

byqmnocz2#

var counter = 1;

var dropdownOptions = [{
  "Value": "test",
  "Text": "tyty"
}];

$(function() {
  $("#add").click(function() {
    var newRow = $(
      '<tr id="tablerow' +
      counter +
      '" class ="poSet"> ' +
      "<td>" +
      '<label id="CountItems"><strong>' +
      counter +
      "</strong></label>" +
      "</td>" +
      '<td width="40%">' +
      '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
      counter +
      ']" id="ItemId[' + counter + ']" required="required" ' +
      "</select>" +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control Qty" name="Qty[' +
      counter +
      ']" value="1" id="Qty[' + counter + ']" data-QtyId= ' + counter + ' required="required" />' +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control" name="MeasureBy[' +
      counter +
      ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
      counter +
      ']" value="0.00" id="UnitPrice[' + counter + ']"  data-PriceId= ' + counter + '  required="required" />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control LineTotal" name="Line_Total[' +
      counter +
      ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
      "</td>" +
      "<td>" +
      '<button type="button" class="btn btn-danger" onclick="removeTr(' +
      counter +
      ');">x</button>' +
      "</td>" +
      "</tr>"
    );

    var selectElement = newRow.find("select");

    dropdownOptions.forEach(function(option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    newRow.appendTo("#submissionTable");

    selectElement.select2();

    counter++;
    return false;
  });
});

//onchange of qty & unitprice
$(document).on("change", ".Qty , .UnitPrice ", function() {
  var element = $(this).closest("tr");
  var qty = element.find(".Qty").val();
  var unit_price = element.find(".UnitPrice").val();
  var total = qty * unit_price;
  element.find(".LineTotal").val(parseFloat(Math.round(total * 100) / 100).toFixed(2));

  calculate_total(); //call function

})

function calculate_total() {
  var sum = 0;
  //looping
  $('[id*=LineTotal]').each(function(el) {
    sum += parseFloat($(this).val()) // adding values
  })
  $("#total").text(sum.toFixed(2)) //added in total div..

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  Total :
  <div id="total"></div>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>
aelbi1ox

aelbi1ox3#

在这种情况下,你可以很容易地编写一个函数来添加一行的所有列:

HTML

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Sample</title>
    </head>

    <body>
        <table>
            <thead>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
            </thead>

            <tbody>
                <tr>
                    <td>Hammer</td>
                    <td>101</td>
                    <td>9.99</td>
                </tr>
                <tr>
                    <td>Screwdriver</td>
                    <td>56</td>
                    <td>4.99</td>
                </tr>
            </tbody>
        </table>

        <button onclick="sumQuantity()">Sum Quantity</button>
        <button onclick="sumPrice()">Sum Price</button>
    </body>
</html>

现在你可以添加一个table helper类,它使用querySelectorquerySelectorAll来获取表的列和行(通过trtd):

class TableUtils {
    #table
    #head
    #body

    constructor(selector) {
        this.#table = document.querySelector(selector)
        this.#head = this.#table.querySelector('thead')
        this.#body = this.#table.querySelector('tbody')
    }

    getCell(row, column) {
        const rows = this.#body.querySelectorAll('tr')
        const selectedRow = rows[row]
        const cells = selectedRow.querySelectorAll('td')
        return cells[column]
    }

    getColumnByHeader(header) {
        const headers = this.#head.querySelectorAll('th')
        const index = Array.from(headers).findIndex(th => th.textContent === header)
        const rows = this.#body.querySelectorAll('tr')
        return Array.from(rows).map(row => row.querySelectorAll('td')[index])
    }

    sum(column) {
        if (typeof column === 'number') {
            let sum = 0
            for (let i = 0; i < this.rowCount; i++) {
                const cell = this.getCell(i, column)
                const value = parseFloat(cell.textContent)
                if (isNaN(value)) {
                    continue
                }
                sum += value
            }
            return sum
        } else if (typeof column === 'string') {
            const cells = this.getColumnByHeader(column)
            let sum = 0
            for (let i = 0; i < cells.length; i++) {
                const value = parseFloat(cells[i].textContent)
                if (isNaN(value)) {
                    continue
                }
                sum += value
            }
            return sum
        }
    }

    get rowCount() {
        return this.#body.querySelectorAll('tr').length
    }

    get columnCount() {
        return this.#head.querySelectorAll('th').length
    }
}

接下来,您需要添加函数来对数量行和价格行求和:

function sumQuantity() {
    const table = new TableUtils('table')
    const sum = table.sum('Quantity')
    alert(sum)
}

function sumPrice() {
    const table = new TableUtils('table')
    const sum = table.sum(2)
    alert(sum)
}

sumQuantity使用表头“Quantity”来计算其总和,而sumPrice使用列索引来计算整个列的总和。
~希望这有帮助

相关问题