【问题标题】:How to perform calculation on a for loop jinja template field using javascript如何使用 javascript 对 for 循环 jinja 模板字段执行计算
【发布时间】:2020-01-29 07:17:03
【问题描述】:

我有一个使用 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

【问题讨论】:

    标签: javascript python for-loop flask jinja2


    【解决方案1】:

    您对每个表格行使用相同的name。附加另一个标识符(例如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 %}
    

    【讨论】:

    • 我现在的主要挑战是将此表单发送到数据库表,因为有多个表单字段具有相同的name
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多