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

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

ReactJS with conditional closing tags

Here is a sample json response : {id: 1, name: a} {id: 2, name: b} {id: 3, name: c} {id: 4, name: d} {id: 5, name: e} {id: 6, name: f} I am looking to organize these by pairs in my React component like so : <div className="group-item"> ...

In order to achieve a sliding effect for the second div, it can be programmed to

Currently, I am working on implementing hide and show functionality in my project. However, I have come across a bug in my code that I need assistance with. When clicking on the first div element, the content opens from bottom to top instead of the desired ...

Issues related to the performance of React, Redux, and three.js

UPDATE: After identifying the issue, I have narrowed it down to this small gist and this jsfiddle. In my real-time 3D game based on three.js, I intended to utilize Redux for state management. Despite creating a simple prototype for testing purposes, even ...

Difficulties encountered with CSS transitions when using the background

I stumbled upon some interesting examples on Stack Overflow about the fade effect on link hover. Curious, I decided to try it out myself and created this JSFiddle. <div class="fade"/> .fade { -o-transition: 0.3s; -moz-transition: 0.3s; -khtml-tran ...

Node.js Express - handling middleware callbacks using next()

When working with Node.js Express and using app.use functions, you may wonder why you don't have to include the 'req' and 'res' parameters in the next() function. Normally, you would expect to see something like this: app.use(func ...

Improving React Efficiency: Should You Utilize Memoization of Axios GET Request Using useMemo or useCallback?

My Objective: I am currently working on a sizable function named getUnitedStatesCases, which involves making an Axios GET Request and performing various operations with the received data. I have already implemented it within a useEffect hook upon componen ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

The watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...

Tips on updating the color of the drawer component's background in Material-UI using React

I have been attempting to change the background color of a drawer component in React, but I have only been successful in changing the background behind the drawer or the field with the items. Here is the code I am using: const useStyles = makeStyles({ ...

Having difficulty adjusting the margin-top for the menu div

Why am I unable to apply margin to my a links within the div identified by id="menu". I can successfully implement margin-left, but when attempting to use margin-top or margin-bottom, it does not work as expected. I wish to adjust the position o ...

What is the common approach for directing a setState Redux action?

I am looking to streamline my state update actions in multiple react-redux reducers by creating a general setState action. This will allow me to have consistent syntax for dispatching both local and redux scope updates. For local updates, I would use this. ...

MUI React: The Smallest Date Possible

Is there a way to ensure that the user cannot select a To Date that is earlier than the From Date? Below are my Two Date Pickers, with date formatting done using moment. <DatePicker v ...

I am experiencing an issue with the LinkedIn Javascript API where it is not providing the

Could it be that the endDate of positions is causing the script to hang? function importJobsEducation() { IN.API.Profile("me") .fields(["id","positions:(company,title,summary,start-date,end-date,is-current)", "educations","skills", "headline"]) ...

Establish a connection between a single EC2 instance running a Node.js application and another EC2 instance acting as a PostgreSQL

Currently, I have two running EC2 instances. One is running a Postgres server and the other is hosting a NodeJS app that needs to connect to the Postgres database. However, it appears that the connection cannot be established as I am unable to ping the P ...

Is it possible to achieve a height transition using CSS instead of relying on JavaScript

I created these custom cards using a combination of HTML, CSS, and JavaScript. However, I've noticed that the height transition animation is not as smooth as I'd like it to be, especially on certain pages. Is there a way to achieve this animation ...

Is it common for content to duplicate when using the 'position: fixed' property in CSS media print?

Consider the following div element: ... <div id='section-to-print'>CONT /*Content*/ </div> ... Accompanied by this CSS code snippet: @media print { * { -webkit-transition: none !important; ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...