Skip to content
Advertisement

TypeError: Cannot read property ‘addEventListener’ of null when i want to add new elements to my database

I created a form to create new post from the auth users however im getting this error “Uncaught TypeError: Cannot read property ‘addEventListener’ of null” and cant seem to know why my script is at the end of the HTML and its an external file, I’ve used eventListener in other places and it work just fine. I’ve even checked for spelling errors but to no avail.

 const createForm = document.querySelector('#create-form');
  createForm.addEventListener('submit', (e) => {
   console.log("hey you clicked p")
     e.preventDefault();
      db.collection('guides').add({
       title: createForm['title'].value,
        content: createForm['content'].value
   }).then(() => {
    // close the create modal & reset form
     const modal = document.querySelector('#modal-create');
      M.Modal.getInstance(modal).close();
       createForm.reset();
   }).catch(err => {
    console.log(err.message);
    });
 });

this is my html

<!-- CREAT A NEW POST -->
<div id="modal-create" class="modal">
   <form class="modal-content animate"  method="post">
    <div>
    <span onclick="document.getElementById('modal-create').style.display='none'" class="close" title="Close Modal">&times;</span>
  </div>
  <div class="container">
    <h4>Create Post</h4><br/>
    <form id="create-form">
      <div class="input-field">
        <input type="text" id="title" required>
        <label for="title">The Subject</label>
      </div>
      <div class="input-field">
        <textarea id="content" class="materialize-textarea" required></textarea>
        <label for="content">The Content</label>
      </div>
      <button class="btn yellow darken-2 z-depth-0">Create</button>
</form>

Advertisement

Answer

You have a form within a form, which is bad and I think in this case, a typo

Try removing <form class="modal-content animate" method="post"> and see if that clears things up

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement