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 databas
Don't inline the event handler!
Also getElementsByName is plural and returns a collection:
document.getElementsByName("total")[0].value
Remove the inline event and instead use
//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"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;
If you do not use total anywhere else, do
var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
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"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
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"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
title 1
1-1-2018
2-2-2018
Event 1
Place 1
100
title 2
2-2-2018
3-3-2018
Event 2
Place 2
200
Total cost
Total