In my project I had created two files to validate the form fields of each page, for example Register and Modify, I made it independent so as not to load everything in the same JS file. At the time it worked for me, it validated correctly and added the classes correctly, today I am reviewing everything to deliver the work (It is evaluative of the university), and Oh! surprise, the validation of the form does not work for me, I am checking and the files are well linked, calling the objects seems to be well linked because in the browser console I write the variable with which I capture (For example the form), and if I it shows normal, however when executing the submit event, it tells me the same error.
Uncaught TypeError: Cannot read property 'addEventListener' of null
As a solution that I have found in this forum and others tell me to validate if the object comes,
const formRegistrar = document.getElementById('formRegistrar');
if(formRegistrar){
formRegistrar.addEventListener('submit', (e)=>{
if(!validar()){
e.preventDefault();
}
});
}else{
alert('Formulario registrar no existe');
}
The issue is that whenever I open any page of my project, I get the alert, that is, as if the constant formRegistrar
were empty.
UPDATE: I forgot to put my HTML code
<form class="p-5 bg-light style-form" id="formRegistrar" method="POST">
<button type="submit" class="btn btn-primary" name="btnRegistrar">
Registrar
</button>
</form>
I appreciate your help. Stay tuned.
Well in view that I already put my question and that it is not recommended to delete questions, then I will find the solution that occurred to me and that worked for me.
SOLUTION: My project is built using the MVC pattern working with PHP, it turns out that I have a file called Template, in which I include each of the page modules of my project (to work with the friendly URL theme), the error was due to that when I was on the home page, it was effectively not loading the objects of my Register page, therefore JS could not find the object which it was associating to the constant. What I did was, invoke the JS file directly on my corresponding page, in this way the error disappeared and the functions run normally.
That's how it was with the error.....
TEMPLATE PAGE
Now I show you how I did to solve it, I simply invoke the file in its corresponding page and remove it from my template file.
REGISTRATION PAGE
MODIFY PAGE