JavaScript - Checkbox loop not totalling up prices correctly

前端 未结 1 418
囚心锁ツ
囚心锁ツ 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);
      }
    })
    <form id="booking" method="get">
      <section id="book">
        <h2>Select Events</h2>
    
        <div class="item">
          <span class="eventTitle">Carmen </span>
          <span class="eventStartDate">2020</span>
          <span class="eventEndDate">2020</span>
          <span class="catDesc">T</span>
          <span class="venueName">Mill </span>
          <span class="eventPrice">3</span>
          <span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
        </div>
        <div class="item">
          <span class="eventTitle">Ash</span>
          <span class="eventStartDate">202</span>
          <span class="eventEnd">2020-12-31</span>
          <span class="catD">Exhib</span>
          <span class="venueNa">The Biy</span>
          <span class="eventPr">0.00</span>
          <span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
        </div>
      </section>
    
      <section id="Cost">
        <h3>Total</h3>
        Total <input type="text" name="total" size="20" readonly="">
      </section>
    </form>

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