【问题标题】:jQuery: get all values from input array and calculate them to variablejQuery:从输入数组中获取所有值并将它们计算为变量
【发布时间】:2020-12-16 19:30:42
【问题描述】:

我有多个输入数组(参见 sn-p)。我需要将所有输入的值计算为变量。这是一个发票创建,所以我想知道所有打折商品的总价。我怎样才能做到这一点?

这是我现在拥有的:

$('#addNewPosition').on('click', function(e) {
            e.preventDefault();
            $('#positions').append('<input type="text" name="item[]" placeholder="Item" class="form-control">\n' +
                '            <input type="number" step="any" name="price[]" placeholder="Price" class="form-control">\n' +
                '            <input type="number" name="item_discount[]" placeholder="Discount, %" class="form-control">\n' +
                '            <input type="number" step="any" name="quantity[]" placeholder="Quantity" class="form-control">\n' +
                '            <input type="text" name="quantity_index[]" placeholder="Unit" class="form-control">\n' +
                '            <input type="text" name="description[]" placeholder="Description" class="form-control">\n');
        });

// Get the number of all items added:
var count = $("input[name='item[]']").map(function() {
  return $(this).val();
}).get().length;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="positions">
  <input type="number" step="any" name="price[]" placeholder="Price" class="form-control">
  <input type="number" name="item_discount[]" placeholder="Discount, %" class="form-control">
  <input type="number" step="any" name="quantity[]" placeholder="Quantity" class="form-control">
  <input type="text" name="quantity_index[]" placeholder="Unit" class="form-control">
  <input type="text" name="description[]" placeholder="Description" class="form-control">
  <a href="#" id="addNewPosition" class="btn btn-green">Add new</a>
</div>

我想要实现的只是计算总价:total = ((每个字段的价格) - 折扣,%) * 数量

有什么办法可以做到吗?亲切的问候

【问题讨论】:

  • 您希望它何时显示?在用户与输入交互时单击按钮或自动更新后?
  • 你想在哪里看到结果?在控制台中?在某些元素中?
  • 你为什么使用.length 那是给你刚刚创建的数组长度。你应该在 map 之后使用 reduce()
  • 这是在我的模式中,然后我想将它传递给父级@Anton。我正在使用长度来确定数组的长度,因为我认为我可以使用for 循环

标签: javascript jquery


【解决方案1】:

这是另一种解决方法。但这是在 VanillaJS 中,你可以把它变成 Jquery。

(function(){

  let addNewButton = document.getElementById("addLineButton");

  let baseItem = document.getElementById("_base");
  let container = document.getElementById('content');

  function createItem(idNumber){
    let newItemNode = baseItem.cloneNode(true);
    newItemNode.id = "_" + idNumber;
    container.insertBefore(newItemNode, document.getElementById("totals"));

    document.querySelectorAll(".editable").forEach((input)=>{
      input.addEventListener("keyup", (event)=>{
        performCalculation(input);
      });
    })
  }

  addNewButton.addEventListener('click', (event)=>
  {
    let currentItemCount = document.getElementsByClassName("item-container").length;
    createItem(currentItemCount);
  });

  function performCalculation(input)
  {
    var cId = input.closest("tr.item-container").id; // container id <tr>
    var qtyVal = document.querySelector(`#${cId} .quantity input`).value;
    var priceVal = document.querySelector(`#${cId} .price input`).value;
    var discountVal = document.querySelector(`#${cId} .discount input`).value;
    var lineTotalElement = document.querySelector(`#${cId} .total input`);
    if(qtyVal && discountVal && priceVal)
    {
      lineTotalElement.value= Number((priceVal * (1 - (discountVal/100))) * qtyVal).toFixed(2);
      performTotal();
    }
  }

  function performTotal()
  {
    let element = document.getElementById("totalPrice");
    let totalPrice = Number(0);
    document.querySelectorAll(".item.total input").forEach((linePrice)=>{
      totalPrice += Number(linePrice.value);
    });
    element.value = totalPrice.toFixed(2);
  }
})();
tr input{
  border: none;
  border-bottom: 2px solid gray;
  padding: 0.25rem;
}
tr td:last-child input{
  background-color: whitesmoke;
}


tr#totals{
  border-top: thin solid gray;
  padding: 0.25rem 0; 

}
#_base{
  display: none;
}
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
    <link href="./src/styles.css" rel="stylesheet" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
</head>

<body>
    <table class="table table-light">
        <thead>
            <tr>
                <th scope="col" class="item description">Description</th>
                <th scope="col" class="item quantity">Quantity</th>
                <th scope="col" class="item price">Price</th>
                <th scope="col" class="item discount">Discount</th>
                <th scope="col" class="item total">Line Total</th>
            </tr>
        </thead>
        <tbody id="content">
            <tr id="_base" class="item-container">
                <th scope="col" class="item description">
                    <input class="editable" placeholder="Description" />
                </th>
                <th scope="col" class="item quantity">
                    <input class="editable" placeholder="Quantity" />
                </th>
                <th scope="col" class="item price">
                    <input class="editable" placeholder="Unit Price" />
                </th>
                <th scope="col" class="item discount">
                    <input class="editable" placeholder="Discount" />
                </th>
                <th scope="col" class="item total">
                    <input disabled />
                </th>
            </tr>
            <tr id="totals" class="item-container">
                <th scope="col" >
                </th>
                <th scope="col" >
                </th>
                <th scope="col" >
                </th>
                <th scope="col" >
                    Line Total
                </th>
                <th scope="col" class="item overallTotal">
                    <input id="totalPrice" disabled />
                </th>
            </tr>
        </tbody>
    </table>
    <button id="addLineButton">Add Line</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="src/index.js">
    </script>
</body>

</html>

Find Codesandbox here

【讨论】:

    【解决方案2】:

    您可以委托输入事件,以便在每次价格或折扣发生变化时计算总和。

    为了获得您的结果,您可以将.map() 与.reduce() 结合使用

    $('#addNewPosition').on('click', function (e) {
        e.preventDefault();
        $('#positions').append('<div class="form-group">' +
                '<div class="col-sm-1"></div><div class="col-sm-3"><input type="text" name="item[]" placeholder="Item" class="form-control"></div>\n' +
                '            <div class="col-sm-1"><input type="number" step="any" name="price[]" placeholder="Price" class="form-control"></div>\n' +
                '            <div class="col-sm-1"><input type="number" name="item_discount[]" placeholder="Discount, %" class="form-control"></div>\n' +
                '            <div class="col-sm-1"><input type="number" step="any" name="quantity[]" placeholder="Quantity" class="form-control"></div>\n' +
                '            <div class="col-sm-1"><input type="text" name="quantity_index[]" placeholder="Unit" class="form-control"></div>\n' +
                '            <div class="col-sm-3"><input type="text" name="description[]" placeholder="Description" class="form-control"></div>\n' +
                '</div>');
    });
    
    $(document).on('input', 'input[name="price[]"], input[name="item_discount[]"], input[name="quantity[]"]', function (e) {
        var price = $('input[name="price[]"]').map(function (idx, ele) {
            return $(ele).val().trim().length == 0 ? 0 : parseFloat($(ele).val().trim());
        }).get();
        var discount = $('input[name="item_discount[]"]').map(function (idx, ele) {
            return $(ele).val().trim().length == 0 ? 0 : parseFloat($(ele).val().trim());
        }).get();
        var quantity = $('input[name="quantity[]"]').map(function (idx, ele) {
            return $(ele).val().trim().length == 0 ? 0 : parseFloat($(ele).val().trim());
        }).get();
        var total = price.reduce(function (a, v, i) {
            return a + (v - (v * discount[i] / 100)) * quantity[i];
        }, 0);
        console.log('total=' + total);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <div id="positions">
        <div class="col-sm-1">
            <input type="number" step="any" name="price[]" placeholder="Price" class="form-control">
        </div>
    
        <div class="col-sm-1">
            <input type="number" name="item_discount[]" placeholder="Discount, %" class="form-control">
        </div>
    
        <div class="col-sm-1">
            <input type="number" step="any" name="quantity[]" placeholder="Quantity" class="form-control">
        </div>
    
        <div class="col-sm-1">
            <input type="text" name="quantity_index[]" placeholder="Unit" class="form-control">
        </div>
    
        <div class="col-sm-3">
            <input type="text" name="description[]" placeholder="Description" class="form-control">
        </div>
    
        <a href="#" id="addNewPosition" class="btn btn-green">Add new</a>
    </div>

    【讨论】:

    • 感谢您的回复!没有数量,我尝试添加一个var quantity = $('input[name="quantity[]"]').map(function(idx, ele) { return $(ele).val().trim().length == 0 ? 0 : parseFloat($(ele).val().trim()); }).get();并在返回return (a - (v * discount[i] / 100)) * quantity;,但总数是NaN
    • 我在您的代码 sn-p 中输入了123(价格)、10(折扣)、3(金额),它显示了total=1230。看起来很奇怪
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2014-06-13
    • 2013-03-27
    • 2012-08-21
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多