Insight on the process of submitting interactive forms

I'm facing a challenge that I can't seem to figure out

It's a form structured in HTML like this:

<button (click)="addform()">add form</button>
<div class="conten-form">
 <div class="MyForm">

  <label>Name</label>
  <input type="text" class="name">

  <label>Description</label>
  <input type="text" class="description">

  <label>Photo</label>
  <div class="img-cont">

   <div class="img">
    <img src="{{img}}">
   </div>

   <div class="addimg">
     <input type="file" (change)="createimg($event)">
   </div>

  </div>
 </div>
 <div class="AddForm"></div>
 <input type="buttom" value="send" (click)="sendform()">
</div>

This is how it looks in TS:

img : any; //to display
imgfile : any; //for form submission
constructor(...){...}
addform(){
 let addform = document.querySelectorAll('.AddForm');
 let myform = document.querySelectorAll('.MyForm');
 let cloneform = myform.cloneNode(true);

 addform.appendChild(cloneform);
}

createimg(event){
 this.imgfile = event.target.files[0];
 const reader = new FileReader();
 reader.readAsDataURL(this.imgfile);
 reader.onload = () => {
    this.img = reader.result;
 };
}

sendform(event){
 let name = document.querySelectorAll(".name");
 let description = document.querySelectorAll(".description");
 let formdata = new FormData;

 //populate formdata with input values from the 'name' class
 for (let i = 0; i < name.length; i++) {
  let stringname = (name[i] as HTMLTextAreaElement).value;
  formdata.append('name',stringname);
 }

 //populate formdata with input values from the 'description' class
 for (let i = 0; i < description.length; i++) {
  let stringdesc = (description[i] as HTMLTextAreaElement).value;
  formdata.append('description',stringdesc );
 }
 //submit the form
}

I'm able to add more forms using the button, but when it comes to adding an image preview dynamically after selecting a file, I'm stuck. The functionality works only for the first form and not for the dynamically added ones. How can I fix this issue considering all data needs to be submitted together in one formdata request? Your help would be highly appreciated.

Answer №1

Avoid using the following code snippets:

 const formList = document.querySelectorAll('.FormList');
 const customForm = document.querySelectorAll('.CustomForm');
 const clonedForm = customForm.cloneNode(true);

Instead of this, consider creating individual components for each form. Take a look at my previous question on Stack Overflow for a better understanding.

You can also refer to this StackBlitz example for a practical demonstration.

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

Ways to modify the pre-defined value in a TextField

I encountered a situation where I have a form with pre-filled data from a specific country. The data is initially read-only, but the user can click on the edit button if they wish to make changes. The issue arises when trying to edit the value in the Text ...

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Alert popup onclick feature is malfunctioning

SOLVED: I finally figured out the issue and it is now working perfectly. I had to manually switch to Chrome instead of using the Brackets live viewer. I want an alert box to pop up when the "Home" link is clicked on my website. I tried creating a separate ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Can values be manually inserted into session storage for the purpose of local testing?

I typically work on my local eclipse and local IDEs such as Sublime Text, using XAMPP locally for development. Since local code does not involve authentication and other complex aspects, I am considering manually injecting session storage values into my we ...

When capturing photos using h5 on iOS devices, the browser may experience a flash back issue

I have been searching Baidu and Google for a while now, but I still haven't found a solution. Here is the specific issue: When using h5 to take photos on iOS systems, the browser flashes back. HTML Code <img src="xxx" onclick="sta ...

Having trouble locating the module 'monaco-editor/esm/vs/editor/editor.worker' while using create react app

I am currently facing some challenges running react-monaco-editor in my project despite following the documentation and making necessary adjustments to my files. Below is a snippet of my package.json file: { "name": "chatbot_compiler", "version": "0. ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

How can one include a URL as a "URL parameter" when using Express?

In my Node.js application, I've set up a router to listen for requests at api/shorten/: router.get('api/shorten/:longUrl', function(req, res, next) { console.log(req.params.longUrl); } When I enter something like: http://l ...

Learn how to effectively share an image using the Math.random function

Is there a way to display a random number of images on a webpage using JavaScript? Let's say we want to show X number of images, where X is a randomly generated number. For the sake of this example, let's set X to be 10. <input class="randomb ...

Developing a slideshow with PHP and JQuery

Attempting to create a simple manual slideshow where the user clicks "next" to advance to the next slide. I have over 50 images and want to display them in batches of 8. For example, the first batch of 8 will be shown initially, then the user can click "ne ...

Just systems that have been positively identified

Greetings! I am currently in the process of creating a small online stock management system using PHP. However, my goal is to restrict access to this web app to only certain systems that I designated. I want to ensure that only the systems under my contro ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Problems arise when JQuery fails to function properly alongside ajax page loading

While utilizing ajax to load the page, I encountered an issue where the jQuery on the loaded page template was not functioning until the page was manually refreshed. The ready function being used is: jQuery(document).ready(function() { jQuery(' ...

Using the useQuery() function in a Next.js React app successfully fetches data from the API on the client side, yet the same API call fails to work when implemented in getServerSideProps on

I am attempting to retrieve data from the backend server using React Query within Next JS getServerSideProps. Here is the function used to fetch the data: export const getGoogleAuthUrl = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC ...

Listening for dates in NodeJS and triggering callbacks

Is there a method or module available that allows me to monitor the date and trigger a specific action when a certain condition is met without relying on setTimeOut? What I am looking for: if(currentHour==="08:00:00"){ doJob() } EDIT : To clarify, wha ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...