Jump to content

addEventListener null issues


ben03

Recommended Posts

Hi there,

  I am sure this is a fairly simple fix, but so far haven't solved it. I am trying to capture the submit of a form. The form is in the html. This is the Javascript:

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('form');
    form.addEventListener('submit', function(e){
      
    }); 
});
      

I would have thought using DOMContentLoaded would have meant form is not null, but always seems to return this. I have tried including the JS file in the <head> and at the end of the <body> but this dosen't make a difference.

If I wrap the event listner in if(form != null) the event listner is never triggered because at the time of the page load it is null so ignores it. Is this because I am doing this locally and not in a server environment?

I really don't want to use inline onlick attribute or 

document.addEventListener('click', function(e) {

as realise this isn't great practice. Enlightenment would be greatly accepted.

Thanks

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...