You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript复选框选中项data-price求和计算功能故障求助

Fixing Your Checkbox Total Calculation Issue

Hey there! Let's walk through the problems in your code and get that total sum working properly. Here's what was going wrong, plus the corrected code:

Key Issues in Your Original Code

  • Case Mismatch: Your HTML form has an ID of BookingForm (uppercase B), but your JS was looking for bookingForm (lowercase b) — so it couldn't find the form at all.
  • Incorrect Event Binding: You tried to bind a click event to l_form.CheckValue, but there's no element with that name/ID in your HTML. Checkboxes should use the change event (triggers when their checked state changes), and we can use event delegation for cleaner code.
  • Undefined Variables: l_checkboxes was never declared, and you were selecting div.item instead of the actual checkboxes.
  • Broken Selectors & Undefined Variables: t_ckbox wasn't defined anywhere, and you used a data-value selector when your checkboxes have data-price attributes.
  • String Concurrency: dataset.price returns a string, so adding them would concatenate text instead of summing numbers (e.g., "13.00" + "16.00" = "13.0016.00"). We need to convert these to numbers first.
  • Wrong Target for Total: You tried to assign the total to l_form.submit.value, but there's no submit element in your form — we need to target the total input instead.

Corrected Code

HTML (unchanged)

<form id="BookingForm" method="get">
  <section id="bookEvents">
    <div class="item">
      <input type='checkbox' name='event[]' value='6' data-price='18.50'>
      <input type='checkbox' name='event[]' value='14' data-price='13.00'>
      <input type='checkbox' name='event[]' value='11' data-price='35.00'>
      <input type='checkbox' name='event[]' value='9' data-price='16.00'>
    </div>
  </section>
  <section id="checkCost">
    Total <input type="text" name="total" size="10" readonly>
  </section>
</form>

JavaScript

window.addEventListener('load', function () {
  "use strict";
  // Fix case mismatch for form ID
  const l_form = document.getElementById('BookingForm');
  const totalInput = l_form.querySelector('input[name="total"]');
  
  // Use event delegation on the form to listen for checkbox changes
  l_form.addEventListener('change', function(e) {
    // Only run if the changed element is a checkbox with data-price
    if (e.target.type === 'checkbox' && e.target.hasAttribute('data-price')) {
      calculateTotal();
    }
  });

  function calculateTotal() {
    let l_total = 0;
    // Get all checked checkboxes with data-price attribute
    const checkedCheckboxes = l_form.querySelectorAll('input[type="checkbox"][data-price]:checked');
    
    // Loop through each checked box and sum the prices
    checkedCheckboxes.forEach(checkbox => {
      // Convert dataset.price to a number before adding
      l_total += parseFloat(checkbox.dataset.price);
    });
    
    // Format the total with £ symbol and update the input
    totalInput.value = `£${l_total.toFixed(2)}`;
  }
});

What This Corrected Code Does

  1. Fixes the Form ID: Uses the correct uppercase BookingForm to grab the form element.
  2. Event Delegation: Listens for change events on the form, so we don't have to bind events to each checkbox individually (works even if checkboxes are added dynamically later).
  3. Proper Selector: Targets only checked checkboxes with the data-price attribute.
  4. Number Conversion: Uses parseFloat() to convert the string price to a number, ensuring proper arithmetic instead of text concatenation.
  5. Correct Target Assignment: Updates the total input with a formatted string including the £ symbol, and uses toFixed(2) to keep two decimal places for currency.

内容的提问来源于stack exchange,提问作者user12505223

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:54:37