首页  >  问答  >  正文

修订后的标题:根据复选框选择计算总计

我正在开发一个简单的财务跟踪应用程序。在应用程序中,有一个包含所有支出账单的表格,然后是位于表格外部的总金额。

我正在尝试找到一种使用 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 天前3477

全部回复(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
  • 取消回复