Having trouble with the addEventListener function not working on a vanilla JS form?

I'm struggling to get a form working on a simple rails project.

The idea is to collect a name and date from the form and display them on the same page using JS. Later, I'll process this information to determine if it's your birthday and calculate how many days are left until your next one.

When the page first loads in localhost, the JS doesn't seem to load properly as it can't find the form. I see this error message in the console related to the form ID:

Uncaught TypeError: Cannot read property 'addEventListener' of null

After filling out the form the first time, nothing happens. But if I refresh the page or submit the form a second time, everything works fine. The URI changes from localhost:3000/page to localhost:3000/page?. I've added preventDefault in my JS script, so I'm puzzled about why this issue occurs.

I attempted to add a condition at the beginning of the JS script where it checks if the form exists before proceeding. This resolves the initial console error, but the script still doesn't work on the first page load.

Thank you for any advice you can provide.

Here's the HTML code for the form:

    <div class="js-form">
        <form id= "new_test_form">
            <div class="mb-3">
                <label for="username" class="form-label"> Your Name</label>
                <input type="text" class="form-control" id="username">
            </div>
            <div class="mb-3">
                <label for="dateinput" class="form-label">Your birth date</label>
                <input type="date" class="form-control" id="dateinput">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
    <div class="results">
    Results will be displayed here
    </div>

And here's the JS:

console.log('Hello from My bdtest')

const form2 = document.querySelector("#new_test_form");
const result = document.querySelector(".results"); 

if (form2) {
  form2.addEventListener("submit", (event) => {
  event.preventDefault();
  const fn_form = document.querySelector("#username").value
  const age_form = document.querySelector("#dateinput").value
  const nd = new Date(age_form)
  console.log(fn_form);
  console.log(age_form);
  console.log(nd.toDateString());
  result.insertAdjacentHTML("beforeend", `<p> Your Name is <strong>${fn_form}</strong></p>` );
  result.insertAdjacentHTML("beforeend", `Your date of birth is ${age_form}` );
  });
}

Answer №1

Have you checked if the JS is loading before your HTML? It might be causing issues with finding #new_test_form. You can resolve this by enclosing your JS code within:

window.onload = function() {
  //your code here
};

Answer №2

Big shoutout to @tihu for the valuable contribution. Thanks to your guidance, I was able to steer in the right direction. Upon further investigation, I discovered a more specific event to monitor :

    document.addEventListener("turbolinks:load", (event) => {
      console.log("Turbolinks turboed ✌");
    });

Now, the form is functioning flawlessly all the time 👍, including during the initial page load.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

In need of assistance with Ember data! Struggling to deserialize JSON into model

Here is the technology stack I'm currently using: Ember 1.10.0 Ember Data 1.0.0-beta.15 Within my application, I have defined a model as shown below: //models//acceptedtask.js import DS from "ember-data"; export default DS.Model.extend({ userAg ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

Challenges faced with Vuetify's vertical and non-linear stepper components

I've been struggling to grasp the concept of Vuetify's stepper feature. Despite my efforts, I haven't been successful in combining different steppers from their page that each have elements I need but lack others. One example is this one on ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Nodejs: A function is expected in the instanceof check, but an undefined value was provided

Encountering a peculiar error while using node-webkit, here's a detailed example to replicate it: index.js: var jQuery = require('jquery'); var Backbone = require('backbone'); (function($){ var ListView = Backbone.View.extend( ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

Express encounters difficulties loading JavaScript files

I'm currently working on building an express web app, but I'm encountering a problem with importing a javascript file. Within board.js, there's a line const utility = require('./utility');. However, this line is causing an error: ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Javascript continues to conceal my web background without my permission

After loading my webpage, I click on a link and the expected javascript runs as planned. However, once it completes and presents the results, the page goes blank to a white screen displaying only the outcomes. My goal is to have these results showcased o ...

Error: Trying to access the parent node of an undefined property

After incorporating this script into my webpage for the newsletter sign-up process, I aimed to reveal customized content post user subscription. <script> function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode ...

What are the optimal strategies for managing various components within an Angular (2) Web application?

I am seeking advice on Angular 2+ Webapps and have a few questions. What is the recommended approach for managing a publicly available info page, an authentication page, and a protected page for signed-in users? Should I consider separate Angular Apps ...

Develop an Engaging JavaScript Quiz with Elements That are Generated Dynamically

** Need help setting answer values for checkboxes Currently, I have a code that displays (2) questions with (4) possible answers each. Next to each answer is a checkbox with a default value of false. However, I want to link the value of each checkbox to ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service. After receiving the data in the controller, I'm using $scope to pass it to the view. Strange behavior - console.logs inside the 'then' function display the data correctly ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

Dynamically hiding elements within tabs using jQuery

Previously, I created a functionality for handling a single set of tabs. However, as the application has expanded, this functionality is no longer sufficient to accommodate multiple sets of tabs. The initial function looked like this: var iconTabs = func ...