2

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")

1
  • You have edited the question - but now the original code is gone... Commented Apr 3, 2017 at 14:13

2 Answers 2

1

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);
}
<div class='item'>
  <span class='eventTitle'>title 1</span>
  <span class='eventStartDate'>1-1-2018</span>
  <span class='eventEndDate'>2-2-2018</span>
  <span class='catDesc'>Event 1</span>
  <span class='venueName'>Place 1</span>
  <span class='eventPrice'>100</span>
  <span class='chosen'><input type='checkbox' name='event[]' value='id1' data-price='100' /></span>
</div>
<div class='item'>
  <span class='eventTitle'>title 2</span>
  <span class='eventStartDate'>2-2-2018</span>
  <span class='eventEndDate'>3-3-2018</span>
  <span class='catDesc'>Event 2</span>
  <span class='venueName'>Place 2</span>
  <span class='eventPrice'>200</span>
  <span class='chosen'><input type='checkbox' name='event[]' value='id1' data-price='200' /></span>
</div>
<section id="checkCost">
		<h2>Total cost</h2>
		Total <input type="text" name="total"  size="10" readonly />
	</section>

Sign up to request clarification or add additional context in comments.

8 Comments

Sir, it still doesn't work, what i do is remove the onclick = total() and then add your code to the following function. 'function total(){ var cal = document.getElementsByName('event[]'); var total = 0; for (var i = 0; i<cal.length; i++){ if(cal[i].getAttribute("data-price").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; }'
Also you have another error if (cal[i].checked) { not if(cal[i].getAttribute("data-price").checked)
Appreciated but when i checked on the checke box, nothing happen, no error show on the console too.
Please use the <> snippet editor in your question and post the view source of at least two checkboxes, the total field and the JavaScript
See my snippet - you need to add the total to the total field
|
0

Why would you use so much '\' ? and what the asterisks '*' after total() for? I have tried following snippet and it seems to works well. (only changing the echo line in your php code)

echo "\t<div class='item'>
            <span class='eventTitle'>".filter_var($event['eventTitle'], FILTER_SANITIZE_SPECIAL_CHARS)."</span>
            <span class='eventStartDate'>{$event['eventStartDate']}</span>
            <span class='eventEndDate'>{$event['eventEndDate']}</span>
            <span class='catDesc'>{$event['catDesc']}</span>
            <span class='venueName'>{$event['venueName']}</span>
            <span class='eventPrice'>{$event['eventPrice']}</span>
            <span class='chosen'><input type='checkbox' name='event[]' value='{$event['eventID']}' data-price='{$event['eventPrice']}' onclick='total()*'/></span>
      </div>\n";

1 Comment

the '\' is used to string escape, when i remove it, it's gv me total() is not a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.