On this line:
$("totaalprijs").innerHTML = totaal1 + totaal2;
...you're trying to use a variable, totaal1
, that isn't declared anywhere. Hence the ReferenceError
, if you try to read the value of a variable that isn't declared, it causes that error.
To fix it, declare the variable (and ideally assign it a meaningful value), or don't use it in that calculation. (And then do the same for totaal2
, because it doesn't seem to be declared anywhere, either.)
Now, the fun thing here is that if the change
event fires on gerecht1
and gerecht2
, totaal1
and totaal2
will get implicitly created as global variables, via The Horror of Implicit Globals. But because those change handlers aren't attached until after the code causing the problem, they never get attached, because of the error.
FWIW, I think you probably wanted something like this:
var totaal1 = 0, totaal2 = 0;
var $ = function (id) {
return document.getElementById(id);
};
var updateTotaalPrijs = function() {
$("totaalprijs").innerHTML = totaal1 + totaal2;
};
updateTotaalPrijs();
$("gerecht1").onchange = function () {
var aantal = parseFloat($("gerecht1").value); // Or possibly `parseInt(..., 10)`
var prijs = 7.9;
console.log(aantal);
totaal1 = aantal * prijs;
updateTotaalPrijs();
};
$("gerecht2").onchange = function () {
var aantal = parseFloat($("gerecht2").value); // Or possibly `parseInt(..., 10)`
var prijs = 9.9;
console.log(aantal);
totaal2 = aantal * prijs;
updateTotaalPrijs();
};
And also FWIW, I would suggest using function declarations most of the time, and wrapping everything to avoid creating globals:
(function() {
var totaal1 = 0, totaal2 = 0;
function $(id) {
return document.getElementById(id);
}
function updateTotaalPrijs() {
$("totaalprijs").innerHTML = totaal1 + totaal2;
}
updateTotaalPrijs();
$("gerecht1").onchange = function () {
var aantal = parseFloat($("gerecht1").value); // Or possibly `parseInt(..., 10)`
var prijs = 7.9;
console.log(aantal);
totaal1 = aantal * prijs;
updateTotaalPrijs();
};
$("gerecht2").onchange = function () {
var aantal = parseFloat($("gerecht2").value); // Or possibly `parseInt(..., 10)`
var prijs = 9.9;
console.log(aantal);
totaal2 = aantal * prijs;
updateTotaalPrijs();
};
})();