Tips for retrieving the value of dynamically added input fields

I am facing some challenges with JavaScript. I want to dynamically add a form to my HTML document when the user clicks on a button. Here is the code I have written:

plusBtn.addEventListener('click', () => {
    const newLine = document.createElement('div');
    newLine.classList.add('line');
    newLine.innerHTML = `
        <textarea form="shopForm" class="form-control form-data" name="comment" id="comment" rows="3" placeholder="Comment" required></textarea>
        <input form="shopForm" type="text" class="form-control form-data" name="price" id="price" placeholder="Price" required>
        <input form="shopForm" class="form-data" type="number" name="amount" id="amount" required>`;
    dataForm.append(newLine);
});

Furthermore, I need to format the form data in a custom way with multiple items. The issue I am facing is that since the inputs are dynamically added using JavaScript, I am unable to access them using .querySelectorAll.

dataForm.addEventListener('submit', function(e) {
    e.preventDefault();
    console.log(window);
    const formData = new FormData(dataForm),
            comment = document.querySelectorAll('.form-comment'),
            price = document.querySelectorAll('.form-price'),
            amount = document.querySelectorAll('.form-amount');

    console.log(comment);

    formData.append('product_url', productUrl.value);
    formData.append('user_id', userId);
    formData.append('delivery_type_id', delivery.value);
    formData.append('package_type_id', package.value);
    if (comment.length > 1) {
        let items = [];
        comment.forEach((item, i) => {
            let obj = {};
            obj.comment = item.value;
            obj.price = price[i].value;
            obj.amount = amount[i].value;
            items.push(obj);
        });
        formData.append('items', JSON.stringify(items));
    } else {
        let items = [];
        items.push({
            'comment': comment[0].value,
            'price': price[0].value,
            'amount': amount[0].value
        });
        formData.append('items', JSON.stringify(items));
    }

    dataAjaxSend(formData)
        .then((response) => {
            console.log(JSON.parse(response));
        })
        .catch((err) => console.log('Error' + err))
});

I am seeking guidance on creating and accessing dynamically added inputs. Thank you for your assistance)

Answer №1

Just because you've created the DOM nodes using JavaScript doesn't mean you can't access them. They are present and accessible. The issue lies in using

document.querySelectorAll('.form-comment')
without adding that class when creating it.

plusBtn.addEventListener('click', () => {
    const newLine = document.createElement('div');
    newLine.classList.add('line');
    newLine.innerHTML = `
        <textarea form="shopForm" class="form-control form-data form-comment" name="comment" id="comment" rows="3" placeholder="Comment" required></textarea>
        <input form="shopForm" type="text" class="form-control form-data form-price" name="price" id="price" placeholder="Price" required>
        <input form="shopForm" class="form-data form-amount" type="number" name="amount" id="amount" required>`;
    dataForm.append(newLine);
});

It's also advisable to avoid using the same ID for elements, as IDs should be unique. Without using labels for these elements, IDs are not necessary.

Answer №2

You forgot to include the class when using it in the .querySelectorAll method, causing a small mistake.

newLine.innerHTML = `
    <textarea form="shopForm" class="form-comment form-control form-data" name="comment" id="comment" rows="3" placeholder="Comment" required></textarea>
    <input form="shopForm" type="text" class="form-price form-control form-data" name="price" id="price" placeholder="Price" required>
    <input form="shopForm" class="form-amount form-data" type="number" name="amount" id="amount" required>`;

Check and execute the code snippet below for a clearer understanding.

const plusBtn = document.getElementById('plus')

const dataForm = document.getElementsByTagName('form')[0]

plusBtn.addEventListener('click', () => {
    const newLine = document.createElement('div');
    newLine.classList.add('line');
    newLine.innerHTML = `
        <textarea form="shopForm" class="form-comment form-control form-data" name="comment" id="comment" rows="3" placeholder="Comment" required></textarea>
        <input form="shopForm" type="text" class="form-price form-control form-data" name="price" id="price" placeholder="Price" required>
        <input form="shopForm" class="form-amount form-data" type="number" name="amount" id="amount" required>`;
    dataForm.append(newLine);
});

const submitFunc = function(e) {
    e.preventDefault();

    const formData = new FormData(dataForm),
            comment = document.querySelectorAll('.form-comment')[0],
            price = document.querySelectorAll('.form-price')[0],
            amount = document.querySelectorAll('.form-amount')[0];

    console.log(comment);

    formData.append('product_url', productUrl.value);
    formData.append('user_id', userId);
    formData.append('delivery_type_id', delivery.value);
    formData.append('package_type_id', package.value);
    if (comment.length > 1) {
        let items = [];
        comment.forEach((item, i) => {
            let obj = {};
            obj.comment = item.value;
            obj.price = price[i].value;
            obj.amount = amount[i].value;
            items.push(obj);
        });
        formData.append('items', JSON.stringify(items));
    } else {
        let items = [];
        items.push({
            'comment': comment[0].value,
            'price': price[0].value,
            'amount': amount[0].value
        });
        formData.append('items', JSON.stringify(items));
    }

    dataAjaxSend(formData)
        .then((response) => {
            console.log(JSON.parse(response));
        })
        .catch((err) => console.log('Error' + err))
    return false
}

dataForm.addEventListener('submit', submitFunc)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <button id="plus">Plus</button>
    <form>
      <input name="dummy" value="dummy" />
      <input type="submit" />
    </form>
    <script src="script.js"></script>
  </body>
</html>

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

Is the custom attribute event being triggered too soon?

My Unique Component Creation Journey I have meticulously crafted a custom component to enhance the navigation of my application. The core structure consists of an ul element, with each li item dynamically generated based on the contents of the router&apo ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Adjust the position of the xAxis on the Highcharts chart to move it downward or

I recently inherited some code from the previous developer that uses highcharts.js (v3.0.1). I'm having trouble with the xAxis appearing within the graph itself (see screenshot). Despite my efforts to recreate this issue in jsfiddle, I can't seem ...

Passing a sophisticated data structure to the controller, where some of the attributes are derived from a separate partial view

I have a model for my view that includes information about appointments and their recurrence. It looks something like this: public partial class AppointmentModel { public appointment Appointment { get; set; } public appointmentRecurrence Rec ...

Innovative Functions of HTML5 LocalStorage for JavaScript and TypeScript Operations

Step-by-Step Guide: Determine if your browser supports the use of localStorage Check if localStorage has any stored items Find out how much space is available in your localStorage Get the maximum storage capacity of localStorage View the amount of space ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...

Transferring selected text to a Cordova application from a different application

Can I extract highlighted text from a different application, such as a browser, and send it to my Intel XDK Cordova app in JSON format for utilization? (Potentially utilizing a context menu) ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

Inquiries about ngshow and the scope concept

I have a question about using AngularJS. I have multiple sections and only want to display one at a time using <section ng-show="section6_us"> </section> and <section ng-show="section7_us"> </section>. My scope has many variables. ...

'Error: Object does not have access to the specified property or method 'values'

I've been working on writing some code to retrieve and read a JSON file. It seems to work fine in Chrome, but I'm running into issues with IE11, which is the browser I need to use. I've tried changing variable names, but the problem persists ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

Accessing information from MySQL using JSONArray and PDO!

After researching on the Internet, I discovered that many people recommend switching from the old mysql (and mysqli) extensions to PDO. Although I am new to PDO, I have learned some basics about it. However, when trying to solve my issue by searching thro ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

The canvas element on a simple HTML webpage is constantly set to a size of 300x150

In an attempt to simplify my problem, I have created a basic HTML document with a <canvas> element: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { border: 1px solid #ff5500; ...

Trouble Displaying DHtmlX Scheduler Events on Safari and Internet Explorer

I have recently embarked on the journey of building a nodejs application and decided to incorporate DHtmlX Scheduler as my calendar. To my dismay, I encountered an issue where the events are not displaying on Safari or IE, despite working perfectly fine on ...

Error encountered in my JavaScript file - Unexpected Token < found on line 1 of the loadash.js script

I am right at the end of creating a sample dashboard with charts using dc.js, but I have hit a roadblock with one error remaining. This error is causing an issue. Unexpected token < on line 1 for loadash.js. The loadash.js file is valid, but for som ...

Step-by-step guide on transforming a raw hexadecimal image into an HTML img tag

I have a raw hexadecimal representation of an image, such as: "FF00FF00FF00" Each pair of letters represents the color of one pixel. For example, in this case it is 6 pixels alternating between white and black, forming a 2x3 pixel grid (width x height). ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...