Creating a duplicate form when a user clicks using JavaScript

https://i.sstatic.net/xhwy7.png

  createNewForm() {
     const newDiv = document.createElement('div');
     newDiv.appendChild(document.createTextNode('Some different text'));
     newDiv.setAttribute('class', 'bg-secondary');
     document.getElementById('mainForm').appendChild(newDiv);
  }

I am working on a form project, where I need to dynamically add a similar form when clicked. Once all values are filled in, the forms will be submitted to the database.

Answer №1

To implement this functionality, you can use the code snippet below (make sure to include validation as well, but here is a basic working example https://stackblitz.com/edit/angular-p3cztw):

HTML Code:

<div *ngFor="let item of formDataList; let i = index;">
  <form>
    <input type="text" [(ngModel)]="item.detail" name="detail" />
    <input type="text" [(ngModel)]="item.amount" name="amount" />
    <input type="date" [(ngModel)]="item.date" name="date" />
    <button (click)="removeItem(item)"> remove </button>
  </form>
</div>

<form #addForm="ngForm">
  <input type="text" [(ngModel)]="data.detail" name="detail" />
  <input type="text" [(ngModel)]="data.amount" name="amount" />
  <input type="date" [(ngModel)]="data.date" name="date" />
  <br/>
  <button (click)="addItem(data)"> add </button>
</form>

TypeScript Code:

public data = {};
public formDataList = [];

addItem($item) {
  this.formDataList.push($item);
  this.data = {};
}

removeItem($item) {
  this.formDataList.splice(this.formDataList.indexOf($item), 1);
}

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

How to toggle hidden links with AngularJS or vanilla JavaScript with a click事件

When the "Show all" button is clicked, I would like to display all elements. If the "1st half" link is clicked, I want to show "abc", "def", and "ghi". When the 2nd link "2nd half" is clicked, I want to display "jkl", "mno", and "pqr". Then, when the "show ...

Anticipated the presence of a corresponding <div> within the server's HTML nested in another <div>

I've encountered a troubling error on my website while using Next.js. The error is causing layout issues and upon investigation, it seems that the device detection hook is at fault. Here's the hook in question: const isBrowser = typeof window !== ...

What is the reason for the compatibility issue between sass-loader and Angular?

One of my rules for dealing with sass is as follows: { test: /\.(scss|sass)$/, use: [ { loader: 'raw-loader'}, { loader: 'sass-loader', options: {data: sassConfiguration} } ], } typescript loader { ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Unexpected results are being produced in React due to code, functions are not being executed upon pressing the submit button

Whenever I click on the Upload button without entering the country code and selecting a file, it displays an alert requesting to "please enter the code and choose the file". However, once I input these fields and then click on the Upload button, this metho ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

Relocate the number of records displayed per page next to the pagination controls in datatables

Currently, I am utilizing datatables to create tables effectively using their provided example. However, I am encountering difficulty in moving the "records per page" element, which is contained within a "span6" class of bootstrap. I understand that this ...

I'm encountering some issues with routing within Node.js and Express framework

I have developed a single page application (SPA) using React framework. Currently, I am working on creating an API with Express in Node.js for my app. Below is the code snippet of my server: const express = require('express'); const app = expr ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

"Uncaught ReferenceError: $ is not defined - $function()" error in JavaScript/jQuery

When attempting to execute a JavaScript/jQuery function, an error is encountered when using Firebug: $ is not defined $(function()". The issue arises from the placement of the JavaScript code within a file named core.js that is referenced by index.php. W ...

Trouble with Ionic 2 and Angular 2: Why isn't my view reflecting variable changes?

Having recently started using Angular 2, I may not fully grasp what's going wrong. In my code, I have an *ngIf statement that is intended to display a button if a certain variable is false and hide the button if the variable is true. However, even af ...

The visibility of MeshPhongMaterial is currently not displaying

As a beginner in the world of THREE.js, I am attempting to create a sphere that will serve as the foundation for a globe with texture. However, I have hit a roadblock while trying to implement MeshPhongMaterial, as nothing seems to appear on the screen. On ...

Loading a page with a Chitika ad using Jquery can cause site malfunctions

I am experiencing an issue with my header.php file on my website. I included another PHP file for my ad code, but it seems to load the ad and then redirect me to a blank page. Can someone please review my code and let me know if there is an error? Thank yo ...

How to override or redefine a TypeScript class with generics

Presently, I am immersed in a project involving three.js and TypeScript. It has come to my attention that for organizing elements, the Group class is highly recommended. However, I have noticed that the type definitions for Group do not include a feature l ...

What is the best way to handle errors in the front-end when receiving responses from expressjs?

Here is the issue that I am facing: //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { ...

Navigating to a Different Vue or Page with Vue Form Wizard

I'm currently exploring VUE JS and trying to figure out how to redirect to another vue or page after submitting a form. I've been working with the sample code provided at https://stackblitz.com/edit/vue3-form-wizard-demo?file=src%2FApp.vue. Whil ...

Locking state object and properties as read-only in ReactJS/Typescript

I have an object from a third-party class and I want to ensure that its properties are read-only. This means that I do not want to be able to change the state with this.state.object.props = "xx"; The structure of the object is as follows: class ThirdPart ...

Viewing documents stored on the file server using the frontend interface (angular)

I am currently working on an Angular application that interacts with a .NET Core API. I have encountered an issue where the file upload process successfully uploads files to a file server, but I am unable to access these files on the front end. Despite at ...

What is the solution to the TypeScript error stating that there is no index signature with a parameter of type 'string' on the 'Object' type?

While working on an Angular project, I came across an issue when writing a Typescript function for a service. The error message stated: "Element implicitly has an 'any' type because expression of type 'string' can't be used to inde ...