Question about callbacks

I have an order form
http://fixmysite.us/Web_Programming_With_Javascriipt/Assignment7
Im tring to do 2 things, calculate the total ande print a reciept.
Heres my thinking

function calculateTotal(callback) {

var Quantity = document.getElementById("Quantity").value;
const Tax = .085;
var Price = 4.95;
var Discount, SubTotal, Total, TotalAfterDiscount;
var Reciept = document.getElementById("reciept");

if(Quantity < 10 ) {
	Discount = 0;
} else if (Quantity < 20 ) {
	Discount = .1;
} else if (Quantity < 30) {
	Discount = .2
} else if (Quantity < 40) {
	Discount = .3
} else if (Quantity < 50 ) {
	Discount = .4;
} else if (Quantity < 60) {
	Discount = .5;
} else if (Quantity < 70 ) {
	Discount = .6;
} else if (Quantity < 80) {
	Discount = .7;
} else if (Quantity < 90 ) {
	Discount = .8;
} else if (Quantity < 100) {
	Discount = .9;
}

SubTotal = (Price * Quantity);

Total = SubTotal + (SubTotal * Tax);

TotalAfterDiscount = Total - (Total * Discount);

callback();

}
function printReciept() {

var First_Name = document.getElementById("First_Name").value;
var Last_Name = document.getElementById("Last_Name").value;
var phone1 = document.getElementById("phone-1").value;
var phone2 = document.getElementById("phone-2").value;
var phone3 = document.getElementById("phone-3").value;
var Phone = "("+phone1+") "+phone2+"-"+phone3;

//make the form dissaoear
document.getElementById("Order_form").style.display = "none";
//make the reciept appear
Reciept.style.display = "block";
//display name
Reciept.innerHTML = "<h3><span>Name:</span>"+FirstName+" "+LastName+"</h3>";
Reciept.innerHTML += "<h3><span>Phone:</span>"+Phone+"</h3>";
Reciept.innerHTML += "<h3><span>Quantity:</span>"+Quantity+"</h3>";
Reciept.innerHTML += "<h3><span>Discount:</span>%"+(Discount * 100)+"</h3>";
Reciept.innerHTML += "<h3><span>Yax:</span>$"+Tax.toFixed(2)+"</h3>";
Reciept.innerHTML += "<h3><span>Total:</span>"+TotalAfterDiscount+"</h3>";

}

But when it runs, I get an error
Reciept is not defined
I thought I used the function printReciept correctly as a callback function though. So shouldnnt it see the same variables as the other function?

No, you’ve defined Receipt within another function (calculateTotal). either pass it to the callback as a a parameter:

  callback(Receipt);
}

function printReciept(Receipt) { 
  ...
  Reciept.style.display = "block";
  ...
}

or just move:

var Reciept = document.getElementById("reciept");

up into the global scope.

I recommend you read: https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

And by the way, I’d change Receipt to receipt. In JS an initial capital denotes a constructor function (i.e. functions that will be used with the new keyword).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.