簡體   English   中英

在計算中使用輸入字段的值,並將結果顯示在另一個元素中

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

我有一個購物車,每個產品都有價格、數量和小計字段。 數量字段可由用戶更改,但其他字段為 static。

當用戶更改數量時,有沒有辦法計算小計? 我想將數量乘以價格,然后更新小計,而不需要用戶提交表單。 此外,在計算小計時,也應更新總計。

這里的視覺表示這里的視覺表示

我的代碼是一個 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>

您需要做的第一件事是對您的 HTML 代碼進行小改動。 由於您將列出多個產品,每個產品都有自己的價格、數量和小計,因此您需要使用class或數據屬性而不是id ,因為id對整個文檔是唯一的,並且一個 ID 只能使用一次。 相關代碼(循環內)應如下所示:

<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>

您還需要更新表格頁腳,以便總單元格獲得數據屬性:

<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 = () => {
  // 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM