Search code examples
javascripthtmlnulltypeerroraddeventlistener

script.js:3:20 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')


I want to submit an HTML form and have a message read depending on the value in the input and text area. However, I'm getting this TypeError telling me the event listener is null even though it's not. Can anyone see where I went wrong?

let recommendationForm = document.getElementById("recommendationForm");

recommendationForm.addEventListener("submit", (e) => {
    e.preventDefault();

    let name = document.getElementById("name");
    let recommendation = document.getElementById("recommendation");

    if (name.value == "" || recommendation.value == "") {
        alert("Input a value in both fields!");
    } else {
        alert("Recommendation submitted successfully!");
        console.log(`${name.value} submitted their recommendation`);
    };

    name.value = "";
    recommendation.value = "";
});
<form action="" id="recommendationForm" class="recommendationSubmission">
  <input type="text" id="name" name="name" placeholder="Name" autocapitalize="on"/>
  <textarea type="text" id="recommendation" placeholder="Recommendation" rows="5" cols="45" autocapitalize="on" wrap="hard"></textarea>
  <button type="submit" id="button">Submit</button>
</form>


Solution

  • When your JS runs the elements are not created yet in the page. You can move the JS block after the HTML block, or add the JS inside this:

    document.addEventListener("DOMContentLoaded", function() {
      // code...
    });