[英]How to perform calculation on a for loop jinja template field using javascript
我有一个使用 for 循环从数据库中查询的项目列表。 我想将每个项目的价格乘以它的数量以获得新的总价格,并获得 for 循环中所有项目的总价格。 如何使用 JS 实现这一点?
我按照这个例子https://www.jqueryscript.net/form/Do-Calculations-Form-Fields-AutoCalc.html但是,只有 for 循环中的第一个项目正在工作,列表中的其他项目都具有与第一项相同的总数
这是我的代码的一部分
<form name="cart">
<table class="timetable_sub">
<thead>
<tr>
<th>Product</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{% for item in user_cart %}
<tr class="rem1">
<td class="invert">{{item.item_name}}
</td>
<td class="invert"><input type="number" name="qty" value="
{{item.quantity}}">
</td>
<td class="invert"><input type="number" name="price" disabled
value="{{item.amount}}">
</td>
<td class="invert"><input type="text" name="item_total" value=""
jAutoCalc="{qty} * {price}">
</td>
</tr>
{% endfor %}
</tbody></table>
<input type="text" name="sub_total" value=""
jAutoCalc="SUM({item_total})">
</form>
我想在示例https://www.jqueryscript.net/demo/Do-Calculations-Form-Fields-AutoCalc/中实现结果,但我得到了这个https://drive.google.com/file/d/ 1CYl3olVoYk6K-n96zxXpf11B1QWZ7FWA/view?usp=sharing
您对每个表行使用相同的name
。 Append 另一个标识符(例如loop.index
)使它们是唯一的:
{% for item in user_cart %}
...
<input type="number" name="qty_{{ loop.index }}" value="{{item.quantity}}">
...
<input type="number" name="price_{{ loop.index }}"
...
<input type="text" name="item_total_{{ loop.index }}" value=""
jAutoCalc="{qty_{{ loop.index }}} * {price_{{ loop.index }}}">
...
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.