【发布时间】: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