简体   繁体   English

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

[英]Use the value of an input field in calculation, and display the result in another element

I have a shopping cart, with a price, quantity, and subtotal field for each product.我有一个购物车,每个产品都有价格、数量和小计字段。 The quantity field can be changed by the user, but the other fields are static.数量字段可由用户更改,但其他字段为 static。

Is there a way to calculate the subtotal when the quantity is changed by the user?当用户更改数量时,有没有办法计算小计? I want to multiply the quantity with the price, then update the subtotal, without the need for the user to submit the form.我想将数量乘以价格,然后更新小计,而不需要用户提交表单。 Also, when a subtotal is calculated, the total should be updated as well.此外,在计算小计时,也应更新总计。

Visual representation here这里的视觉表示这里的视觉表示

My code is a Django template and looks like this, with the relevant part in the loop:我的代码是一个 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 %}
            <tfoot>
                <tr class="visible-xs">
                    <td class="text-center"><strong>Total 1.99</strong></td>
                </tr>
                <tr>
                    <td colspan="2" class="hidden-xs"></td>
                    <td class="hidden-xs text-center" id="total"><strong>Total </strong></td>

                </tr>
            </tfoot>
        </table>

The first thing you need to do is make a small change to your HTML code.您需要做的第一件事是对您的 HTML 代码进行小改动。 Since you will be listing multiple products, each with its own price, quantity, and subtotal, you need to use class or data attributes instead of id , as id is unique to the entire document and an ID can only be used once.由于您将列出多个产品,每个产品都有自己的价格、数量和小计,因此您需要使用class或数据属性而不是id ,因为id对整个文档是唯一的,并且一个 ID 只能使用一次。 The relevant code (inside the loop) should look something like this:相关代码(循环内)应如下所示:

<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" data-type="price">{{crops_ordered_cost}}</td>
    <td data-th="Quantity">
      <input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}">
    </td>
    <td data-th="Subtotal" class="text-center" data-type="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>

You will also need to update your table footer so the total cell get a data attribute:您还需要更新表格页脚,以便总单元格获得数据属性:

<td class="text-center" data-type="total"><strong>Total <span>0</span></strong></td>

(The span element is needed so we can update the number only.) (需要 span 元素,因此我们只能更新数字。)

The example code below should then do the trick, updating the subtotal when the quantity is changed.下面的示例代码应该可以解决问题,当数量发生变化时更新小计。 The code might not work in Internet Explorer, so let me know if that is a requirement.该代码可能无法在 Internet Explorer 中运行,因此请告诉我是否有此要求。 I also added comments to help clarify what happens where.我还添加了评论以帮助澄清在哪里发生了什么。

// 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 = () => {
  // Find all the subtotals.
  const subtotals = document.querySelectorAll('[data-type="subtotal"]');
  let calculatedTotal = 0;

  // Loop through all the subtotals, and add them to the final total.
  Array.from(subtotals).forEach((subtotal) => {
    calculatedTotal += Number(subtotal.textContent);
  });

  // Then return the total.
  return calculatedTotal;
}

// As above, we use a separate function to calculate the subtotal for a product.
const calculateSubtotal = (product) => {
  // The input event will fire when the value of the quantity field is changed.
  product.addEventListener('input', () => {
    /*
     * With multiple prices and subtototals, we need to look for them going
     * upwards from the quantity field, using the parent elements (first the
     * table cell, then the table row).
     */
    const parentRow = product.parentNode.parentNode;

    // Then find the price and subtotal for this product.
    const price = parentRow.querySelector('[data-type="price"]');
    const subtotal = parentRow.querySelector('[data-type="subtotal"]');

    // And finally, update the subtotal and the total.
    subtotal.textContent = price.textContent * product.value;
    total.textContent = calculateTotal();
  });
}

// Loop through all the quantity inputs and wait for the subtotal to change.
Array.from(quantityInputs).forEach((element) => calculateSubtotal(element));

暂无
暂无

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

相关问题 如何在jQuery的输入字段中显示计算结果? - How to display the calculation result in the input field in jQuery? 如何显示从输入字段的输入值到另一个输入字段的查询结果 - How To Display Query Result From Entered Value of Input Field To Another Input Field 我如何乘以只读输入字段的值并将结果显示在另一个字段中 - How do i Multiply the Value of a readonly input field and display the result in another field 从另一个输入字段值(动态输入字段)在输入字段中设置值Sql查询结果 - Set Value Sql Query Result in Input Field From Another Input Field Value (Dynamic Input Field) 自动填充输入字段和计算结果 - Automatically fill input field with result of calculation 基于输入字段的计算结果 - calculation based on input field for a result on the fly 如何在输入字段内执行特定的数学计算并将结果填充到另一个字段? - How can i perform a specific math calculation inside an input field and populate the result to another? Javascript switch 语句计算由另一个 function 调用以显示结果计算 - Javascript switch statement calculation called by another function to display result calculation 基于输入字段值的不同javascript计算 - Different javascript calculation based on value of input field 获取当前表行的输入字段值,并将其附加到另一个元素 - Get input field value of current table row and append it to another element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM