Home > front end >  Can't include JS file into HTML
Can't include JS file into HTML

Time:01-16

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:

<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?

CodePudding user response:

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.

  •  Tags:  
  • Related