繁体   English   中英

jQuery:从输入数组中获取所有值并将它们计算为变量

[英]jQuery: get all values from input array and calculate them to variable

我有多个输入数组(见代码片段)。 我需要计算所有输入的值到一个变量。 这是发票创建,所以我想知道所有折扣商品的总价。 我怎样才能做到这一点?

这就是我现在所拥有的:

 $('#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>

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

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

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

为了达到你的结果,你可以结合.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>

这是另一种解决方法。 但这是在 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>

在这里找到 Codesandbox

暂无
暂无

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

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