Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't include JS file into HTML

I have simple file structure with HTML and JS files which looks like this:

templates/
 - index.html
 - menuselector.js

Here is an example of function that I want to import into HTML:

export function getTypeOfClient() {
    const select = document.getElementById('inputGroupSelect02');
    const value = select.options[select.selectedIndex].value;
    if (value === '1') {
        document.getElementById('person').style.display = "block";
        document.getElementById('company').style.display = "none";
    } else if (value === '2') {
        document.getElementById('company').style.display = "block"
        document.getElementById('person').style.display = "none";
    } else {
        document.getElementById('person').style.display = "none";
        document.getElementById('company').style.display = "none";
    }
}

Here is an example of HTML code that uses this function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<select class="form-select" id="inputGroupSelect03" onchange="getTypeOfClient()">
     <option value="0" selected>Choose...</option>
     <option value="1">Person</option>
     <option value="2">Company</option>
</select>

When I write my code in script tag, everything works correctly, but I decided to export this code into JS file to make it more clean.

I import this in file like this – <script type="text/javascript" src="menuselector.js"></script>

And here is the problem. Every time in console I get 404 and not found this file. I was trying to import this in header, footer, body etc., but it doesn’t work. What do I do wrong?

>Solution :

You cannot use ES Modules as inline event listeners onchange="getTypeOfClient()" as they don’t get added to the global scope (which is the whole point of modules).

Either explicitly assign it to the global scope using window.getTypeOfClient = getTypeOfClient, or remove the export keyword if you don’t want ES modules.

That being said, using inline event listeners is very bad for a whole bunch of reasons; instead use Javascript to define or add the listener.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading