Wanted to try out using external JS file, but I can't seem to be able to call a function I defined there. Every time I try to call it, an error "Uncaught ReferenceError: calculate (function name) is not defined" is returned. I've been coding for only a week, so trying to figure out my error myself led me nowhere.
Chunks of code:
<head>
<meta charset= "utf-8">
<script type= "text/javascript" src= "nameOfFile.js"></script>
</head
Trying to call the function:
<select type= "select" id = "currency" onchange= "calculate()">
<option value= "RUB", selected> RUB </option>
<option value= "USD"> USD </option>
<option value= "EUR"> EUR </option>
<option value= "GBP"> GBP </option>
The function in external file:
function calculate() {
var currencyName = document.getElementById("currency");
var currency = currencyName.value;
var time = document.getElementById("timeInput");
var sum = document.getElementById("sumInput");
var amount = sum.value;
var income; //pure percent revenue
var earnings; //income + revenue
var result = document.getElementById("results");
var percentage;
switch (currency) {
case RUB:
if (time>= 3 && time <= 5) {
percentage = 5;
}
else if (time >= 6 && time <= 11){
percentage = 6;
}
else if (time >= 12 && time <= 24){
percentage = 6,5;
}
break;
case USD:
if (time>= 3 && time <= 5) {
percentage = 0,1;
}
else if (time >= 6 && time <= 11){
percentage = 0,5;
}
else if (time >= 12 && time <= 24){
percentage = 1;
}
break;
case EUR:
case GBP:
if (time>= 3 && time <= 5) {
percentage = 0,1;
}
else if (time >= 6 && time <= 11){
percentage = 0,25;
}
else if (time >= 12 && time <= 24){
percentage = 0,5;
}
break;
}
income = percentage / 100 * amount;
earnings = amount + income;
}
The page seems to recognize the existence of .js file, I can see it in "Sources" tab in Chrome, for example. Both files are in the same folder.
EDIT: Problem solved, see my answer.
2 Answers 2
Apparently, problem was that I accidentally added some HTML code in the external JS file.
I noticed that I had paragraphs at the bottom (for some reason...) and when I deleted them and fixed commas to dots (thanks, Tristup and Thomas), everything started to work fine.
2 Comments
value= "RUB", selected here should be no ,, these: case RUB: should be strings case "RUB": and should throw errors at the moment, your </head tag is not properly closed, and I don't know wether you just missed to copy the closing </select>-tag, or wether it is missing in your markup.Can you load the script at the bottom or in Footer section of the HTML. May be the function unable to recognize the element that are called into it.
To check that file is included properly. You can write alert("hi"); at the top of the file that included.
Please let me know if you need to know anything more on it.
Thanks and Regards
7 Comments
percentage = 6,5 is perfectly valid JS. But you're right, it does not do what he probably intended/meant.
.jsfile?javascript:change()