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

Using Jquery to swap out div elements and reinitialize code after selecting a menu <a href>link<</a>

I have a jQuery script that swaps out a div when a href="#1" is clicked. The same link, a href="#1", is then replaced by a href="#2" and vice versa. Here is the jQuery code: $('.child2, a[href="#1"]').hide() $('#replacepagelinks a').c ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

Tips for styling buttons in react-admin with custom CSS

I need some help with customizing buttons in react-admin. I am new to the platform and unsure about how to go about changing the button CSS for various actions such as create, edit, and export. Can anyone provide guidance on the best way to customize these ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Update article translation dynamically in Vue without needing to refresh the page

ArticleController public function index() { $locale = Lang::locale(); // $locale = Lang::getLocale(); $articles = Article::withTranslations($locale)->get(); return $articles; } resources/assets/js/pages/articl ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

Optimizing the JSON date structure

After receiving a datetime value in JSON with the format: Created "/Date(1335232596000)/" I developed a JavaScript function to display this value on the front end. Here's the code snippet: return new Date(parseInt(date.substr(6))); However, the c ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...