猿问

使用输入字段的值进行计算,并将结果显示在另一个元素中

我有一个购物车,其中包含每种产品的价格、数量和小计字段。用户可以更改数量字段,但其他字段是静态的。

当用户更改数量时,有没有办法计算小计?我想将数量乘以价格,然后更新小计,而不需要用户提交表单。此外,计算小计时,总计也应更新。

此处的视觉表示

我的代码是一个 Django 模板,如下所示,相关部分位于循环中:


<div class="container">

<table id="cart" class="table table-hover table-condensed">

            <thead>

                <tr>

                    <th style="width:50%">Product</th>

                    <th style="width:10%">Price</th>

                    <th style="width:8%">Quantity</th>

                    <th style="width:22%" class="text-center">Subtotal</th>

                </tr>

            </thead>

{% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %}

            <tbody>

                <tr>

                    <td data-th="Product">

                        <div class="row">

                            <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div>

                            <div class="col-sm-10">

                                <h4 class="nomargin">{{crops_ordered_names}}</h4>

                                <p>Available amount: {{crops_ava}}</p>

                            </div>

                        </div>

                    </td>

                    <td data-th="Price" id="price">{{crops_ordered_cost}}</td>

                    <td data-th="Quantity">

                        <input type="number" class="form-control text-center" id="quan"  min="1" max="{{crops_ava}}">

                    </td>

                    <td data-th="Subtotal" class="text-center" id="subtotal"></td>

                    <td class="actions" data-th="">

                        <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>

                    </td>

                </tr>

            </tbody>

{% endfor %}



慕标5832272
浏览 97回答 1
1回答

胡说叔叔

您需要做的第一件事是对 HTML 代码进行一些小更改。由于您将列出多个产品,每个产品都有自己的价格、数量和小计,因此您需要使用 class 或数据属性而不是 id,如 id 对于整个文档来说是唯一的,并且 ID 只能使用一次。相关代码(循环内)应如下所示:<tbody>&nbsp; <tr>&nbsp; &nbsp; <td data-th="Product">&nbsp; &nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="col-sm-10">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h4 class="nomargin">{{crops_ordered_names}}</h4>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>Available amount: {{crops_ava}}</p>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </td>&nbsp; &nbsp; <td data-th="Price" data-type="price">{{crops_ordered_cost}}</td>&nbsp; &nbsp; <td data-th="Quantity">&nbsp; &nbsp; &nbsp; <input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}">&nbsp; &nbsp; </td>&nbsp; &nbsp; <td data-th="Subtotal" class="text-center" data-type="subtotal"></td>&nbsp; &nbsp; <td class="actions" data-th="">&nbsp; &nbsp; &nbsp; <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>&nbsp; &nbsp; </td>&nbsp; </tr></tbody>您还需要更新表页脚,以便总单元格获得数据属性:<td class="text-center" data-type="total"><strong>Total <span>0</span></strong></td>(需要 span 元素,因此我们只能更新数字。)下面的示例代码应该可以解决这个问题,在数量更改时更新小计。该代码可能无法在 Internet Explorer 中运行,因此请告诉我这是否是必需的。我还添加了评论以帮助澄清在哪里发生的事情。// Find all quantity inputs, and the element where we display the total.const quantityInputs = document.querySelectorAll('[data-type="quan"]');const total = document.querySelector('[data-type="total"] span');// For simplicity, we calculate the total in a separate function.const calculateTotal = () => {&nbsp; // Find all the subtotals.&nbsp; const subtotals = document.querySelectorAll('[data-type="subtotal"]');&nbsp; let calculatedTotal = 0;&nbsp; // Loop through all the subtotals, and add them to the final total.&nbsp; Array.from(subtotals).forEach((subtotal) => {&nbsp; &nbsp; calculatedTotal += Number(subtotal.textContent);&nbsp; });&nbsp; // Then return the total.&nbsp; return calculatedTotal;}// As above, we use a separate function to calculate the subtotal for a product.const calculateSubtotal = (product) => {&nbsp; // The input event will fire when the value of the quantity field is changed.&nbsp; product.addEventListener('input', () => {&nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp;* With multiple prices and subtototals, we need to look for them going&nbsp; &nbsp; &nbsp;* upwards from the quantity field, using the parent elements (first the&nbsp; &nbsp; &nbsp;* table cell, then the table row).&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; const parentRow = product.parentNode.parentNode;&nbsp; &nbsp; // Then find the price and subtotal for this product.&nbsp; &nbsp; const price = parentRow.querySelector('[data-type="price"]');&nbsp; &nbsp; const subtotal = parentRow.querySelector('[data-type="subtotal"]');&nbsp; &nbsp; // And finally, update the subtotal and the total.&nbsp; &nbsp; subtotal.textContent = price.textContent * product.value;&nbsp; &nbsp; total.textContent = calculateTotal();&nbsp; });}// Loop through all the quantity inputs and wait for the subtotal to change.Array.from(quantityInputs).forEach((element) => calculateSubtotal(element));
随时随地看视频慕课网APP

相关分类

Html5
我要回答