Unable to invoke a function declared in an external JavaScript file

Desire to experiment with an external JavaScript file arose, but encountered difficulties in invoking a function defined within. Every attempt at calling it resulted in the error message "Uncaught ReferenceError: calculate (function name) is not defined." With only a week of coding experience under my belt, troubleshooting this issue independently proved fruitless.

Snippets of code:

<head>
    <meta charset= "utf-8">
    <script type= "text/javascript" src= "nameOfFile.js"></script>
</head

Attempting 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 residing in the 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 webpage appears to acknowledge the presence of the .js file, visible in Chrome's "Sources" tab, for example. Both files reside in the same folder.

EDIT: Issue resolved, please refer to my solution below.

Answer №1

It turns out that the issue was caused by inadvertently inserting HTML code into the external JavaScript file.

After realizing there were extra paragraphs at the end (for unknown reasons...), and making some punctuation adjustments as suggested by Tristup and Thomas, the problem was resolved and everything began functioning correctly.

Answer №2

Is it possible to load the script at the bottom or in the Footer section of the HTML? Perhaps the function is unable to recognize the elements that are being called into it.

To verify if the file is included correctly, you can add alert("hi"); at the top of the included file.

Please inform me if you require any further information on this matter.

Thank you and Best Regards

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it true that the react setState function does not function properly with stream data?

I'm currently utilizing PouchDB to synchronize my remote database with my local database. The following code is integrated within the componentDidMount lifecycle method: const that = this var localDB = new PouchDB('localdb') var remoteDB = ...

I am seeking to redirect to a different page within an ejs template by clicking on a link

I am having trouble navigating to the next page using a link and keep getting a 404 error. I recently switched my template from jade to ejs. <html> <body> <div> <ul style="color:white; float: right;" class="nav navbar-nav ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

What is the best way to create a new instance for each incoming HTTP request in NestJS?

While working with my API, I encountered an issue where the classes were not being destroyed after receiving a response. Currently, I am using nestJS, but when I tested nodeJS + expressJS, I also faced the same problem. The code I am using is as follows: ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

Having trouble getting the desired output while iterating through a JavaScript object in search of a specific key and value

Here is an example of how my data is structured: var obj = { QuestionId: 97, SortOrder: { '9': '1' }, directive: { '1': false, '2': false, '9': true }, data: { '1': '', '2 ...

Custom date formatting with jQuery table sorting

I have been using a jQuery plugin called Tablesorter to sort a table. I am facing an issue with sorting dates in the yyyy MMM dd format, especially because my date inputs are in French. Here is an example of how the dates are formatted: 2014 janv. 05 20 ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Encountering Rendering Issues with EJS Post HTML Conversion

After working on a much larger project for over a month, I'm now six hours into troubleshooting and everything is starting to blend together. Prior to switching to EJS, everything was working perfectly. I'm not looking for someone to solve the ...

Creating Angular Modal on ng-click

I'm facing a challenge with a seemingly simple task. Within an ng-repeat, I have a table of events. My goal is to enable users to click on the event name and view detailed information in a modal window. To achieve this, I have set up an ng-click="ev ...

Ensure that the second y-axis in charts.js consistently shows the 100% tick

I have implemented a scatter chart using recharts and it currently looks like this: The right-y-axis in my chart represents the percentage and is showing the correct values as desired. However, I am looking to make a modification so that the 100% mark is ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

What are some alternative ways to redirect multiple pages in a Navbar component in React Js without encountering the 'useNavigate()' error?

How can I resolve this error while working with react js? Error: useNavigate() is only allowed within a <Router> component. ▶ 3 stack frames were collapsed. Navbar C:/Users/dell/OneDrive/Desktop/ReactJs/react-learning/src/components/Navbar.js:9 ...

What is the best way to execute a series of AJAX functions one after the other in JavaScript?

Currently, I am working on a project that involves editing multiple elements within a window simultaneously using AJAX. My goal is to have all "open for editing" elements saved when the user clicks the save button for the entire window. However, I encount ...

Utilize the size of the array as a variable

I have a question regarding the use of the length of an array as an integer value in JavaScript. Here is the code snippet: var counter = 0; var bannerLinks = document.getElementsByClassName("bannerlink"); var linkCount = bannerLinks.length; va ...

The console.log() displays the dictionary correctly, but trying to access it with a key results in it being undefined

I'm currently facing an issue with accessing the dictionary stored in the "workload" field of a document in Firestore. Here is the snippet of code I am struggling with: async addTask() { const projectDoc = await getDoc(doc(db, "projects", "Testing ...

Modify JSON from using single quotes to double quotes using JavaScript

Received a JSON from the backend to the front end that uses single quotes throughout, causing issues with a Magento 2 widget. The JSON structure is as follows: { 'mood': 'happy', 'reason': 'why shouldn't I?'} T ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...