Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I try to add 'addEventListener' on the button immediately after creating it. ( function init() {

    console.log("div created"); 

    // create a new div element
    var newDiv = document.createElement("div");
    newDiv.id = "registration_form";

    var createForm = document.createElement("form");
    newDiv.appendChild(createForm);

    var heading = document.createElement("h2");
    heading.innerHTML = "Registration Form";
    createForm.appendChild(heading);

    var linebreak = document.createElement('br');
    createForm.appendChild(linebreak);

    createElement(createForm, 'label','','','Name: ');
    createElement(createForm, 'text', 'dname', '','');
    createSpanTag(createForm,'nameError');
    breakTag(createForm);breakTag(createForm);
    createElement(createForm, 'label','','','Email: ');
    createElement(createForm, 'email', 'email', '','');
    createSpanTag(createForm,'emailError');
    createElement(createForm, 'button','Validate','Validate','');
    document.getElementsByTagName('button')[0].addEventListener('click',validate());
    document.getElementsByTagName('body')[0].appendChild(newDiv);

}
)();

function createElement(formElement,type,name,value, placeholder) {
if(type=='label'){
    var element=document.createElement(type);
    if(name!='' && value!=''){
        element.setAttribute('name',name);
        element.setAttribute('value',value);
    }
    element.innerHTML=placeholder;
    formElement.appendChild(element);
} else {
    var element=document.createElement('input');
    if(type!=''){
        element.setAttribute('type',type);
    }
    if(name!=''){
        element.setAttribute('name',name);
    }
    if(value!=''){
        element.setAttribute('value',value);
    }
    if(placeholder!=''){
        element.setAttribute('placeholder',placeholder);        
    }
    formElement.appendChild(element);
} 

}

function breakTag(createForm){
createForm.appendChild(document.createElement('br'));
}

function validate(){

}
function createSpanTag(createForm, id){
    var element=document.createElement('span');
    element.setAttribute('id',id);
    createForm.appendChild(element);
}

Answer №1

It is important to remember that the second argument of addEventListener must be a function. Instead of using...

document.getElementsByTagName('button')[0].addEventListener('click',validate())

try using...

document.getElementsByTagName('button')[0].addEventListener('click',validate);

Answer №2

Since the tag name is input and not button, you should use input as a parameter in the function getElementsByTagName(). Then, loop through all nodes to find the node with the attribute type equal to button.

Consider modifying this line:

document.getElementsByTagName('button')[0].addEventListener('click',validate());

to:

var nodeList = document.getElementsByTagName("input");

for (var i = 0; i < nodeList.length; i++)
{
    if (nodeList[i].getAttribute("type") == "button") {
        nodeList[i].addEventListener('click', validate);
    }
}

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

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

What is the correct way to initialize a variable that will store the output of setInterval?

While examining a question, I came across someone's solution that proposed updating the code below. In the comments section, it was suggested: Instead of setting this.tm to undefined, we should set it to 0. Since it's a time interval, it shoul ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

Error: AJAX responseText Mismatch detected

When I make an AJAX call in my code, everything seems to be working correctly. The PHP script responds with "success" when it should, and the response text is indeed "success". However, even though the output appears to be correct, the line if(returnVal == ...

The res.send() function is being executed prior to the async function being called in express.js

My current project involves creating an API that returns epoch time. I am using an express.js server for this, but the issue arises when the res.send() function is called before the getTimeStamp() function finishes executing. I tried looking up a solution ...

Customizing CSS based on URL or parent-child relationship in WordPress

I'm having trouble finding a solution for what seems like a simple issue... Currently, my header has a border-bottom and I'd like to change the color of this border based on the section the user is in. For example, consider these parent pages: ...

Enable the text to wrap around an interactive object that the user can freely manipulate

Looking for a solution where I can have a floating div that can be moved up and down using javascript while the text wraps around it seamlessly. Similar to how an object positioned in a word document behaves, I want the text to flow around the div both ab ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

The toggle button requires two clicks to activate

I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start? Below is t ...

How do I connect to a SOAP WebService in Node.js?

I am embarking on my first journey into accessing a Web Service. Specifically, I am attempting to connect to the Banxico SOAP Webservice in order to retrieve the exchange rate of the peso (M.N.) to the dollar. I am using Node with Express and have been re ...

Retrieve all elements from an array that have the highest frequency of occurrence

Consider an array like [1,4,3,1,6,5,1,4,4]. The element with the highest frequency in this array is 3. The goal is to select all elements from the array that have a frequency of 3, so in this case we would select [1,4]. To achieve this, one possible meth ...

Show specific elements in a listview using JavaScript

I have created a dynamic listview using jQuery Mobile that currently shows 4 list items. The list is generated through JavaScript. $( document ).ready(function() { var data = [{ "name": "Light Control", "category": "category", "inf ...

Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders. Below is my express API Endpoint which should return an array of objects (orders). const bod ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

Eliminate the need for pressing the "tab" key on my website

I'm currently working on a horizontal web page layout and I'm looking for a way to disable the "tab" button functionality on my page. The issue arises because I have a contact form with textboxes located in the last div, and when users navigate u ...

Executing numerous HTTP requests in a single Node.js HTTP request

I am attempting to make a single URL call that will fetch multiple URLs and store their JSON responses in an array, which will then be sent as the response to the end user. Here is what my code looks like: var express = require('express'); var ...

Developing a trivia game using HTML and JavaScript

I'm in need of some serious assistance with creating a quiz using HTML. My goal is to have a web page where users can visit, take a quiz, and have their responses stored. Unfortunately, I don't have the knowledge or skills required to do this on ...