JavaScript - Checkbox loop not totalling up prices correctly

前端 未结 1 416
囚心锁ツ
囚心锁ツ 2021-01-28 17:46

When I click on the checkbox at the top, it puts a \'0\' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop.

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 18:16

    You have no total in the code you provided.

    I would personally use ID when only having one element and if more, use relative addressing and/or delegation

    const form = document.getElementById('booking');
    const total = document.getElementById('total');
    document.getElementById("booking").addEventListener("click", function(e) {
      if (e.target.name === "event[]") {
        let totalprice = 0;
        [...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
          if (box.checked) {
            totalprice += +box.dataset.price;
          } //if
        })
        document.querySelector("[name=total]").value = totalprice.toFixed(2);
      }
    })

    Select Events

    Carmen 2020 2020 T Mill 3
    Ash 202 2020-12-31 Exhib The Biy 0.00

    Total

    Total

    0 讨论(0)
提交回复
热议问题