What is the best way to dynamically retrieve the value from a textbox?

Whenever I click on the ADD button, I am dynamically adding three textboxes. These textboxes are located within the same div tag and each has a different name.

Therefore, every time I click on the ADD button, I create a new div with three textboxes inside it.

Now, I need to be able to access the values entered into these text fields. How can I do that?

    <div class="ord" id="parent">

    </div>
    <button type="button" class="btn btn-primary fa fa-plus add btn-xs"> Add </button> 

JS

   var items = "<form role='form' class='form-inline' style='padding-bottom: 5px;'>"
                    + "<div class='form-group'><input id='med' placeholder='' class='form-control'></div>"
                    + "<div class='form-group' style='padding-left: 5px;'><input id='qua' placeholder='' class='form-control'></div>"
                    + "<div class='form-group' style='padding-left: 5px;'><input id='rem' placeholder='' class='form-control'></div>"

  $('.add').on("click",function(){
div_id = div_id + 1
$( ".ord" ).append('<div id="item'+div_id+'">' + items + '<button style="margin-left: 3px;" type="button" id="item'+div_id+'" class="btn btn-default btn-danger btn-xs fa fa-close" onclick=deleteitem(id)></button></form></div>');
   })

I have an array of IDs for all the div tags, such as [item1, item2, item3].

How can I retrieve the text entered in all the text fields?

Answer №1

Make sure to use the .forEach method and concatenate the id with a "#" when selecting an element in order to create a valid ID selector.

['element1', 'element2', 'element3'].forEach(function(element) {
  $("#" + element).find('input').each(function() {
    console.log(this.value);
  });
});

Note: If element1,... are the id values of parent div elements, remember to use .find('input') to locate descendant <input> elements. You can then use .each to loop through all the found elements and retrieve their value.

Reminder: When calling the deleteitem(id) function, make sure to pass this.id instead of just id.

Answer №2

let elements = ['element1', 'element2', 'element3']; // this is your "list of Ids for all div tags"
elements.forEach(function(element) {
    $('#' + element).find('input[type="text"]').each(function() {
        console.log($(this).val());
    }):
});

You may want to consider adding type="text" to your input fields.


Furthermore, keep in mind that having multiple occurrences of the same id in your code is not recommended.

Below is an improved code snippet to address this issue:

let elements = [];
let divId = 0;

// Create a function to ensure only one instance of #med, #qua, and #rem
function getInputs(id) {
    let inputs = "";
    inputs += '<form role="form" class="form-inline">';
    inputs += '    <div class="form-group"><input type="text" id="med' + id + '" class="form-control" /></div>';
    inputs += '    <div class="form-group"><input type="text" id="qua' + id + '" class="form-control" /></div>';
    inputs += '    <div class="form-group"><input type="text" id="rem' + id + '" class="form-control" /></div>';
    inputs += '</form>';
    
    return inputs;
}

// Click event handler for the Add button
$(".add").on("click", function() {
    let currentId = "item" + divId; // Ensure only one instance of #item0, #item1, etc.
    
    let html = "";
    html += '<div id="' + currentId + '">';
    html += getInputs(divId);
    html += '    <button type="button" data-delete="' + currentId + '" class="btn btn-danger btn-xs">Close</button>';
    html += '</div>';
   
   $(".ord").append(html);
  
   elements.push(currentId);
   divId++;
});

// Click event handler for the Close button
$(document).on("click", "button[data-delete]", function(evt) {
    evt.preventDefault();
    let id = $(this).data("delete");
    
    $("#" + id).remove();
  
    // Remove the element from the list
    let index = elements.indexOf(id);
    if (index !== -1) {
        elements.splice(index, 1);
    }
});


// Change event handler for the input fields
$(document).on("change", 'input[type="text"]', function() {
    elements.forEach(function(item) {
        $('#' + item).find('input[type="text"]').each(function() {
            console.log($(this).attr("id") + " => " + $(this).val());
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>



<div class="ord" id="parent">

</div>
<button type="button" class="btn btn-primary add">Add</button>

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

Guide on how to retrieve server error responses in javascript using axios

I am currently using axios to send form data to a Laravel backend. While I can easily access the response upon success, I am facing difficulties retrieving the error response. In my browser's developer tools, under network > response, I see the fo ...

Using setInterval in React within an onChange event

I am facing a challenge where I need to set a setInterval inside an onChange event, which is typically done in componentDidMount. Currently, I have 2 dropdowns that filter data and then render a table. The dropdowns are controlled by their respective onCh ...

Execute JavaScript unit tests directly within the Visual Studio environment

In search of a method to run JavaScript unit tests within the Visual Studio IDE, I currently utilize TestDriven.net for my C# units tests. It's convenient to quickly view the test results in the output pane and I am seeking a similar experience for Ja ...

Is it possible to create a hyperlink in the <button> element?

Having been immersed in HTML5 for quite a while now, I recently encountered a challenge while working on my login/register page project. I wanted to create a button that would redirect me to another HTML page upon clicking. While I am familiar with the < ...

gallery showcasing pictures with a prominent main image and accompanying smaller images

I am struggling to display my image gallery the way I envision it. I would like to have a larger main image with the rest of the images displayed on the right side below it. The current code I have is: <div class="gallery"> <a href=" ...

Having trouble getting JSON data to display in CanvasJS

I am trying to retrieve JSON data using Ajax with this code. It works fine when fetching data from the original source, but it's not working with my own JSON data. What could I be missing? Any help would be greatly appreciated. Thank you. $(document) ...

Tips for implementing jQuery functions such as lightbox and other features on a page loaded via ajax requests

I have a specific requirement for my page. I designed a section to display various departments, where clicking on $('.getDetails') will reveal a list of employers from each department along with some details. Furthermore, clicking on an employer& ...

Ensure one div scrolls independently while the other remains fixed using Bootstrap

I am currently in the process of constructing a web page with Bootstrap 4. The layout consists of two columns, each contained within individual divs. My requirement is for the content on the right side to be scrollable while the content on the left remains ...

What is the best way to activate a button based on the presence of a cookie?

As I develop my web application, I am faced with the challenge of catering to both guests and registered users. I want to provide a 'Log out' button exclusively for registered users after they have logged in. One solution I am considering is to d ...

Error: Attempting to access the 'filter' property of an undefined value is not permitted in React. This issue has caused an undefined error

I'm encountering an issue with my API call. I'm trying to implement a search bar in my project where the data is fetched from an API. However, when I add a filter function, I encounter an error. Error: Cannot read properties of undefined (reading ...

What is the best way to retrieve AWS secret values using JavaScript?

Having recently started using AWS, I have been able to manually obtain the secret I need. However, when attempting to utilize the code snippet provided by AWS to retrieve the secret value, all my attempts result in undefined. Can someone please point out ...

Using HTML5 and CSS for 3D transformations along with stacking divs to create a unique accordion

Is there a way to stack divs vertically above each other and use CSS3 3D transforms to create a folding effect between them? I've tried rotating the divs on their X axis, but it leaves gaps between each div because they don't collapse into each o ...

Having trouble with Bootstrap dropdowns not opening when clicking with jQuery?

I am in the process of developing a table with multiple rows, each containing an "Options" button to display a dropdown context menu. To streamline the code, I am utilizing a single div to serve as a common markup for the context menu. The technologies I ...

Choose a Date from the Calendar and Modify the Link Text

I have a Link Label on my page that triggers a calendar pop-up when clicked. I want the label to update to the selected date in the format '30 JAN 2017' from the calendar. The issue lies with the local variable var dateText =...; although the la ...

Using Node.js and React to dynamically render a different HTML file in response to a request

We are currently working on implementing AMP pages for our project. Our current solution involves detecting a query in the URL, such as: myurl.com?amp=1, and completely redrawing the page with the necessary markup. However, our server is set up to choose ...

Header contains problem with cross-domain access in $http

Sending a request through Angularjs $http with JSON data to my REST service requires setting headers once the response is returned. The necessary headers are added as follows, Response.ok() .entity(emp) .headers.add("Access-Control-Allow-Origin", "*") .he ...

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

Displaying XML data in an HTML document

I've been experimenting with some code online to extract data from an XML file and display it in a table. However, my implementation is not showing the table as expected based on the examples I've come across. <html> <head> & ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...