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 forbookingForm(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 thechangeevent (triggers when their checked state changes), and we can use event delegation for cleaner code. - Undefined Variables:
l_checkboxeswas never declared, and you were selectingdiv.iteminstead of the actual checkboxes. - Broken Selectors & Undefined Variables:
t_ckboxwasn't defined anywhere, and you used adata-valueselector when your checkboxes havedata-priceattributes. - String Concurrency:
dataset.pricereturns 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 thetotalinput 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
- Fixes the Form ID: Uses the correct uppercase
BookingFormto grab the form element. - Event Delegation: Listens for
changeevents on the form, so we don't have to bind events to each checkbox individually (works even if checkboxes are added dynamically later). - Proper Selector: Targets only checked checkboxes with the
data-priceattribute. - Number Conversion: Uses
parseFloat()to convert the string price to a number, ensuring proper arithmetic instead of text concatenation. - Correct Target Assignment: Updates the
totalinput with a formatted string including the £ symbol, and usestoFixed(2)to keep two decimal places for currency.
内容的提问来源于stack exchange,提问作者user12505223
相关产品推荐
相关产品推荐

