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

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...

What is the reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

What are the drawbacks of automating the process of generating charts to track time spent on webpages?

!RESOLVED! I am looking to automatically generate charts based on users and their time spent on different pages of a website. I have a file named "log.xml" where I store user information (customers), visited pages, dates, and the time they spent; once I ...

Retrieving the path parameter in a Next.js APIabstractmethod

I need assistance with extracting information from the file routes/api/[slug]/[uid].ts Specifically, I am looking to retrieve the slug and uid within my handler function. Can anyone provide guidance on how to achieve this? ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

Optimal row settings for different reports using Material-UI table pagination

Recently, I've been exploring an example involving material-ui's TablePagination. In this scenario, they present a useTable component with the following code snippet: import React, { useState } from 'react' import { Table, TableHead, Ta ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

There seems to be an issue with d3js bar charts as they are not displaying on the screen and there

Recently, I started delving into the world of D3js and decided to try my hand at creating some bar charts. However, despite my efforts, the bar charts failed to display on the screen. <!DOCTYPE HTML> <html> <head> <title> My D3 Pra ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

I'm having trouble resolving the issue in my React App after attempting to export a functional component. How can I troubleshoot and

Since the first week of this online course on Coursera.org, I've been struggling to get my React app to display. Even after watching videos and revising the code multiple times based on Google search results, I couldn't make it work. Despite seek ...

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

How come the state update result is triggering two different responses?

I recently developed a basic TicTacToe game using react-hooks. At times, I notice that the result is displayed before the state update on the screen. Other times, the result shows up after the update is visible on the screen. I'm puzzled by this ...

Substitute all web links contained within the DIV

Is there a way to change the URLs within a specific DIV? Here's an example of what I want to do: <div id="SearchList"> <a href="www.google.com/up">up</a> <a href="www.google.com/down">down</a> <a href="www.google.com/ ...

The Shopify CLI's node serving function has not been operational for a project that is one year old

As I embark on refactoring my previous Shopify project, I encounter an issue when executing the command "shopify node serve" which prompts the following error message. "This command can only be run within node projects." Despite this error message, my pr ...

Using an AngularJS directive to modify CSS styles

I'm attempting to modify DOM CSS styles using Angular. If the textbox value is set as the height, I have assigned ng-model to the textbox and then ng-style="{height:heightdef}" How can I achieve this using a directive? Fiddle :: http://jsfiddle.n ...