I have the following js file:
class UniversityListModals {
test(){
alert("ed")
}
}
const universityListModals = new UniversityListModals();
universityListModals.test();
Which of course brings up the alert window. However on my html form tag, I wish to call this exact same method:
<form method="GET" action="/something/" onSubmit="universityListModals.test()">
However when I press the submit button the console says: "Uncaught ReferenceError: universityListModals is not defined".
How can I call it via js and not directly from the html?
CodePudding user response:
It looks like you are declare your function in a scoped environment, so the DOM can't reach the variable name.
Make sure, that the universityListModals
variable at the global scope.
class UniversityListModals {
test(){
alert("ed")
}
}
const universityListModals = new UniversityListModals();
<form method="GET" action="/something/" onSubmit="universityListModals.test()">
<button type="submit">Submit</button>
</form>
CodePudding user response:
You should check for how the script is loaded in your html page...
But, if you want to make it directly from your js as you asked, you could make something like that.
class UniversityListModals {
test(){
alert("ed")
}
}
document.onload = function(){
const universityListModals = new UniversityListModals();
document.getElementByTagName("form")[0].addEventListener('submit', function(){
universityListModals.test();
}
}