2
votes

I'm doing an app for a class, and the professor is just as confused as I am about why it's not working. I have 2 js files and one html. I'm exporting an array from one js to the other, then using that js as the src in my html. Here's the pertinent code:

medList.js:

export const CompleteMedList = [
.....
];

main.js:

import {CompleteMedList} from './MedList.js'

html:

<script src="main.js"></script>

And here's the error I'm given:

main.js:1 Uncaught SyntaxError: Unexpected token {

I tried using type="module" in the script tag, but then it gives me this error when I try do do stuff using the functions declared in main.js:

Uncaught ReferenceError: openCycleForm is not defined at HTMLButtonElement.onclick

Here's the function that the error references in main.js:

function openCycleForm() {
   document.getElementById("newCyclePg1").style.width = "100%";
   for (var i=0; i < CompleteMedList.length; i++){
       document.getElementById("fullMedsList").innerHTML += 
       "<input type=\"checkbox\" name=\"meds\" id=\"" + CompleteMedList[i].id + "\">" +
       CompleteMedList[i].name + "<br></br>";
   }
}

I initially had the code in the html file (where it worked), but just moved it to main.js so I could use an array of data instead of hardcoding it, and then everything broke...

1
may not solve your entire problem, but for "Uncaught ReferenceError: openCycleForm is not defined at HTMLButtonElement.onclick" have you made sure that your JS file is loaded before the html document if the html is being manipulated by the JS? And/or that your JS uses something like document on load when interacting with the DOM? - TCooper
Hey can you give some more thorough samples of the code. It's hard to tel what's going on from tiny tid bits. Also, format the code correctly :] - Eddie D
I'm going to sound dumb, but how do I make sure the JS file is loaded before the html file? It sounds like that might be the issue. If it is, then I can keep the tyep="module" in there. - fairymay
I did that, and then it gives me Uncaught ReferenceError: openCycleForm is not defined at HTMLButtonElement.onclick - fairymay
There's an issue with your functions in main then, as type="module" solved the other error. If it's not much code add it here, or add it on jsFiddle so we can have a quick look. - Andy

1 Answers

0
votes

It looks like it's being a bit funny with the inline JS, so I suggest you remove it and add the event listeners in main.js instead. Something like this which I have working locally on my machine at the moment:

HTML

<button type="button" class="currentCycle">Current Cycle</button>

JS

const currentCycleButton = document.querySelector('.currentCycle');
currentCycleButton.addEventListener('click', openCurrentCycle, false);

function openCurrentCycle() {
  document.getElementById("currentCycle").style.width = '100%';
  console.log('done');
}