Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here

I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID because it keeps changing whenever I add or remove a jQuery textbox field.

HTML

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

JavaScript

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initial text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

Answer №1

If you want to retrieve all dynamic input elements with the name attribute set to "mytext[]" using JavaScript, you can use the selector ".input_fields_wrap input[name='mytext[]']" along with document.querySelectorAll() and Array.from(), or jQuery() and $.map() to create an array containing the values.

let values = Array.from(
               document
               .querySelectorAll(".input_fields_wrap input[name='mytext[]']")
            , ({value}) => value);

console.log(values);
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="0"></div>
</div>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="1"></div>
</div>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="2"></div>
</div>

let values = $.map($(".input_fields_wrap input[name='mytext[]']")
            , ({value}) => value);

console.log(values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="0"></div>
</div>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="1"></div>
</div>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]" value="2"></div>
</div>

Answer №2

Retrieve the information using a specific name.

For instance:

$('input[name^="mytext"]').each(function() {
    alert($(this).val());
});

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

Issue with spacing when assigning a JavaScript array variable to a value within input tags during a loop

Having some trouble with JavaScript code where the value is not passing in its entirety if there are spaces between the words. How can I make sure the full string or array object gets passed into the input tag's value? This is how I am trying to assi ...

Compiling NPM package for distribution without internet access (including necessary dependencies)

What is the best way to create a tarball package for distribution that includes all dependencies? The package must include the actual module along with all its dependencies, as it will be installed offline within an organization with internet restrictions ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

Tips for resolving vertical alignment styling for images of varying sizes within Vue.js transition-group?

I have created an image slider example, but I'm facing a styling issue when using images of different dimensions. The element leaving the array is positioned absolutely for smooth transitions, but this causes the image to move up. I am trying to vert ...

Unable to modify attribute within $templateCache through an AngularJS Directive

Here is my Directive code: module.directive('iconSwitcher', function() { return { restrict : 'A', link : function(scope, elem, attrs) { var currentState = true; elem.on('click', function() { ...

Error in Node.js: Attempting to access the property 'nick' of an undefined object

The Problem There seems to be an issue when combining the query and variable or using a "fake PDO" style. The Code if(page == "profile"){ var user = "Failed to load."; con.query('SELECT * FROM users WHERE id = &ap ...

RESTful API versus Socket.IO - Which is the better choice?

I am currently developing a mobile application that connects to a node.js server to retrieve data. I am wondering what is the most efficient method for retrieving data from the node.js server? Here is the architecture of my project: MySQL DB <-> N ...

Scrolling automatically

I'm experimenting with creating a typing effect using JavaScript and the typed.js library, found here: My approach involves using a div as a container. However, I've encountered an issue - when the text reaches the height of the div, scroll bars ...

What is the best way to use a JavaScript function as a callback?

I'm struggling with understanding callbacks, especially how they function. Here is my function: function checkDuplicateIndex(values, callback) { $.ajax({ type: "POST", url: url, data: "command=checkIndexAlbumTracks& ...

Could the comments within a NodeJS script be causing memory problems?

I specialize in creating NodeJS libraries, and my coding practice includes adding JSDoc comments for documentation purposes. Here is an example of how my code usually looks: /** * Sum * Calculates the sum of two numbers. * * @name Sum * @function * ...

How to modify an element in an array using NodeJS and MongoDB

**I need assistance updating the "paymentStatus" field within either the "ballpool" or "valorant" game arrays. I am working with NodeJS and would appreciate guidance on how to update the payment status by passing in the value of "ballpool" or "valorant" as ...

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

Learn how to establish a specific time frame for showcasing a success message and directing users to the login page within AngularJS

I want to show the success message for 2 minutes after someone registers and then automatically redirect them to the login page. I attempted to achieve this using the code below but encountered some issues. Here is my updated code snippet. var app = ang ...

Tips for troubleshooting grid display issues in Internet Explorer

.container{ display: grid; grid-template-columns: minmax(200px, 7fr) 4.4fr; grid-column-gap: 64px; } .item{ background: red; height: 100px; } <div class="container"> <div class='item item-1'></div> <div class=&a ...

Storing past entries in a local storage using JavaScript

Currently, I am developing a JavaScript program that involves 3 input boxes. The program is designed to display whatever is typed into each input box on the page. To store and re-display previous submissions, I have implemented local storage. However, I en ...

I found myself continuously revolving four images along a circular border, each time revealing the corresponding content. However, I only required the content from one of the images at a time

I attempted to animate the rotation of a circle and display the content of a specific image by pausing it for a period of time. However, I am unsure how to halt the animation and display the content of the specified image. Here's what I tried: HTML C ...

Guide on how to retrieve Twitter Username and Profile Photo through the Twit NPM Package

Utilizing the twit npm package to retrieve the Authenticated Twitter Username and Profile Image, here is the code I am using: const Twit = require('twit'); let T = new Twit({ consumer_key: 'xxx', ...

The latest version of Ionic, 5.4.16, encounters issues when attempting to run on Ubuntu 20.04 with Node version 12

Initially, I used apt's nodejs package (node 10) to run my Ionic 5 app. However, it seems that node 12 or 14 are required instead. So, I proceeded to install node --channel=12/stable, followed by installing ionic@5 using npm. I then attempted to crea ...