My goal is when a checkbox is clicked it's data-price should be added to the total variable and then this variable should be shown in the total price text box, however, it currently doesn't update the value when a checkbox is clicked.
Here is an interactive example of how it currently works/looks:
const form = document.getElementById('bookingForm');
const total = document.getElementsByName[0]('total');
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let total = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
total += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").innerHTML = total.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
const total = document.getElementsByName('total')[0]other way around, you havedocument.getElementsByName[0]('total').