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}` );
});
}