I'm trying to add the onclick funtion when user checked the check box, and then the total price will be shown.
All the information including price is retrieve from database (no problem with retrieving data, the data display correctly).
Here is how's the code looks like.
//calculate price
function total() {
var cal = document.getElementsByName('event');
var total = 0;
for (var i = 0; i < cal.length; i++) {
if (cal[i].checked) {
total += parseFloat(cal[i].getAttribute("data-price"));
}
}
}
var checks = document.getElementsByName(event);
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="selectEvent">
<h2>Select Events</h2>
<div class ="item">
<span class="chosen">
event1 <input type= checkbox name= event data-price = "1" value=eventId1/>
event2 <input type= checkbox name= event data-price = "2" value=eventId2/>
</span>
</div>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly />
</section>
</form>
here is the java script code,just focus on funtion total()
window.addEventListener('load', initialise);
function initialise () {
'use strict';
//calculate price
function total(){
var cal= document.getElementsByName('event[]');
var total = 0;
for (var i = 0; i<cal.length; i++){
if(cal[i].checked){
total += parseFloat(cal[i].data-price);
}
}
document.getElementByName("total").value = "$" + total.toFixed(2);
}
here is the link for my reference
[1]: Display total price when checkbox clicked in JS
i also tried but it doesn't work
total += parseFloat(cal[i].getAttribute("data-price")