首頁  >  問答  >  主體

修訂後的標題:根據複選框選擇計算總計

我正在開發一個簡單的財務追蹤應用程式。在應用程式中,有一個包含所有支出帳單的表格,然後是位於表格外部的總金額。

我正在嘗試找到一種使用JS 或AJAX 的方法,以便當我選擇表行中的1 個複選框時,我可以在總計中包含/排除賬單,並自動更新總計以反映排除/包含。

表格行是動態建立的,因此每次新增帳單時,行都會增加,這表示核取方塊 ID 需要增加。

<div class="card-body">
  <table class="display table" style="width:100%" id="example">
    <thead class="table-heading">
      <tr class="table-border">
        <th scope="col">#</th>
        <th scope="col">CREDITOR</th>
        <th scope="col">DESCRIPTION</th>
        <th scope="col">CATEGORY</th>
        <th scope="col">AMOUNT</th>
        <th scope="col" style="text-align: center">INCLUDE / EXCLUDE</th>
      </tr>
    </thead>
    <tbody>
      {% for item in debts %}
      <tr class="table-border table-items">
        <td>{{ forloop.counter }}</td>
        <td>{{ item.creditor }}</td>
        <td>{{ item.description }}</td>
        <td>{{ item.category }}</td>
        <td>£{{ item.amount }}</td>
        <td><input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" class="table-checkbox" id="myCheckbox" /></td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

我有一點 JS

const checkbox = document.getElementById('myCheckbox')

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})

當選取複選框時,這確實會觸發警報,但這只會在第一個複選框上觸發,因為這是具有相同 ID 的複選框。

所以這可能是一個棘手的任務,因為我需要複選框 JS 來知道選中復選框的行的金額是多少,然後從總數中減去該數字,反之亦然。也許這是錯誤的方法?

總數顯示為:

<h3 class="text-right text-danger"><i class="mdi mdi-cube icon-size float-left"></i><span class="font-weight-bold">£{{total_monthly_outgoing|floatformat:2}}<span class="h6"> per month</span></span></h3>

謝謝

P粉360266095P粉360266095178 天前3482

全部回覆(1)我來回復

  • P粉759457420

    P粉7594574202024-04-05 11:35:00

    你只需要委派

    我必須在 h3 中展開你的 span,以免 JavaScript 變得非常混亂

    給總數一個ID,這樣比document.querySelector("h3.text-danger span")更容易。

    此腳本不需要 ID

    選取時包含

    const totalContainer = document.querySelector("h3.text-danger span");
    
    document.querySelector(".card-body").addEventListener("click", (e) => {
      if (!e.target.matches(".table-checkbox")) return; // not a checkbox
      const total = [...document.querySelectorAll(".table-checkbox:checked")]
        .map(chk => +chk.closest("td").previousElementSibling.textContent.slice(1)) // remove the pound
        .reduce((a,b)=> a+b); // sum
      totalContainer.textContent = `£${total.toFixed(2)}`;
    })
    .table-checkbox {
      border: 2px dotted #00f;
      display: block;
      background: #ff0000;
    }
    # CREDITOR DESCRIPTION CATEGORY AMOUNT INCLUDE / EXCLUDE
    1 creditor 1 description 1 category 1 £123
    2 creditor 2 description 2 category 2 £223
    3 creditor 3 description 3 category 3 £323

    £0 per month

    回覆
    0
  • 取消回覆