Iterate over each row in order to retrieve the values of dynamically created input fields

Currently, my code involves PHP, JSP, and JSON. I need to extract the values from textboxes so that I can insert them into the database.

Specifically, I am dealing with a table that stores information about siblings. Since the number of siblings varies, I have set up a table that dynamically adds rows and columns with textboxes when a button is clicked.

Below is the HTML code for the table:

<table id="tbSibling">
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Occupation and Employer</th>
        <tr>
            <td><input type="text" id="txtSib10" /></td>
            <td><input type="text" id="txtSib11" /></td>
            <td><input type="text" id="txtSib12" /></td>
            <td><input type="text" id="txtSib13" /></td>
        </tr>
        <tr>
        <td id="btnAdd" class="button-add" onclick="insertSibRow();">Add</td>
            </tr>
        </table>

The script that dynamically adds rows and columns with textboxes is as follows:

<script type="text/javascript">
    // Creating rows and columns dynamically for Table Id: tbSiblings
    function insertSibRow(){
        var table=document.getElementById("tbSibling");
        var lastRow=table.rows.length - 1;
        var row=table.insertRow(lastRow);

        for(var i=0; i<4; i++)
        {
            var cellName=row.insertCell(i);
            var input=document.createElement('input'); 
            input.type='text';
            input.id='txtSib' + lastRow + i ;
            cellName.appendChild(input);
        }
    }
</script>

I assign each input an ID using:

input.id='txtSib' + lastRow + i ;
//result: txtSib10, txtSib11, txtSib12, txtSib13

Now, the challenge lies in extracting values from these dynamically created rows and columns so that they can be passed to a PHP page for insertion into the database.

Currently, it only retrieves the first row. To ensure all rows are captured, I aim to determine the total number of rows by creating an array and pushing the values accordingly.

var lastRow=tblSiblings.rows.length;
var arrSiblings = new array();

for(x=0;x>lastRow;x++){
    arrSiblings[x] = $("#txtSib10").val();
}

The issue arises with this line:

arrSiblings[x] = $("#txtSib10").val();

If anyone can assist with retrieving values from dynamically generated textboxes across rows and columns, your help would be greatly appreciated. Thank you!

Answer №1

When dealing with dynamically generated rows of inputs, my go-to approach involves setting up an array structure for naming all inputs within a form. This helps keep track of each input's data by assigning them an index (starting from 0) alongside their respective names. For instance, you can use something like members[0][name] to label your initial input:

HTML

<table id="tbMember">
    <tbody>
    <tr>
        <td><input type="text" name="members[0][name]" /></td>
        <td><input type="text" name="members[0][age]" /></td>
        <td>
            <select name="members[0][gender]">
                <option>Male</option>
                <option>Female</option>
            </select>
        </td>
        <td><input type="text" name="members[0][occupation]" /></td>
    </tr>
    </tbody>
</table>
<button id="add-member" type="button">Add member</button>

To add a new row, I duplicate the last one in the table, clear the input values, and update the index in their name attribute. Here's an example of how I achieve this:

JS

$('#add-member').click(function(){
    var newRow = $('#tbMember tbody tr').last().clone().appendTo($('#tbMember tbody'));
    var newIndex  = newRow.index();
    newRow.find(':input').each(function(){
        $(this).val('');
        $(this).attr('name', $(this).attr('name').replace(/\d+/, newIndex));
    });
}); 

If you're using AJAX to send the data to your server, utilizing jQuery's $.post() method would be beneficial. Here's how you can implement it:

$.post('process.php',$('#tbMember :input').serialize());

Once the data is received in your PHP script, you can access it as an array under $_POST['members']. From there, you can loop through the data and store it in your database effectively.

PHP

<?php
    $members_data = isset($_POST['members']) ? $_POST['members'] : array();
    foreach($members_data as $member){
         $name = $member['name'];
         $age = $member['age'];
         $gender = $member['gender'];
         $occupation = $member['occupation'];
    }
?>

Answer №2

Wouldn't it make more sense as follows:

for(x=0, y=1; x<4; x++){
    arrSiblings[x] = $("#txtSib" + y + x).val();
}

Answer №3

$("#txtSibling10").val()

Unique identifiers can be found at: https://developer.mozilla.org/en-US/docs/Web/API/element.id

"IDs should be distinct within a document and are commonly used for getElementById searches."

To improve your script that creates the markup, consider using a class name for each text box generated in a loop.

Given that the object being constructed includes information on name, age, phone number, and occupation, it is suggested to assign a class name to each row, iterate through them, and then construct the JSON:

$('.sib-row').each(function() {
  $_siblingsInfo = '{":RELATIONSHIP":"'+"Siblings"+'",":NAME":"'+$(this).find(".name").val()+'",":AGE":"'+$(this).find(".age").val()+'",":TEL_NO":"'+$(this).find(".telno").val()+'",":OCCUPATION":"'+$(this).find(".occupation").val()+'"}';
});

Use a standardized class name for the text fields in every row so that the same code can be applied during iteration:

<table id="tbSibling">
  <th>Name</th>
  <th>Age</th>
  <th>Gender</th>
  <th>Occupation and Employer</th>
  <tr class="sib-row">
    <td><input type="text" class="name" /></td>
    <td><input type="text" class="age" /></td>
    <td><input type="text" class="telno" /></td>
    <td><input type="text" class="occupation" /></td>
  </tr>
  <tr>
    <td id="btnAdd" class="button-add" onclick="insertSibRow();">Add</td>
  </tr>
</table>

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 to conditionally adding a property to an object in JavaScript

After scouring both Stack Overflow and Google for a solution, I finally stumbled upon this brilliant idea: x = { y: (conditionY? 5 : undefined), z: (conditionZ? 5 : undefined), w: (conditionW? 5 : undefined), v: (conditionV? 5 : undefined), u ...

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

Harmonizing database with AJAX-powered webpage

When using ajax calls to update data on a web page, what is the most effective way to synchronize changes with a database? For example, if I have a comment form that needs to work asynchronously. I write JS code to submit the form data to the database, but ...

`res.render when all data queries are completed``

When I make an app.get request in my server.js file, I retrieve a dataset from MongoDB and then render my page while passing the data to it. Here is an example: //page load app.get('/', (req, res) => { //find all data in test table ...

Ensure that all promises are executed with their inner functions

Is there a way to retrieve multiple HTML bodies simultaneously and only start working with the content once all results are available? I have a callback solution that currently works, here is the code: const request = require('request') const ...

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

Why is this specific element showing as undefined in the form during editing, but appearing correctly in both the debugger and console.log?

I've encountered an error that keeps popping up: "Cannot read property 'textContent' of undefined at HTMLDocument". This error specifically occurs when dogName, dogBreed, and dogSex are set within the 'click' listener. It's st ...

No issues encountered during indexing with Elasticsearch Bulk

When I run the code snippet below on the cmd line in Windows to bulk index roughly 3 million documents, nothing seems to happen. The process completes in less than a second without any output, and the index is not created as expected. curl -H "Content-Ty ...

CrossBrowser - Obtain CSS color information

I'm attempting to retrieve the background color of an element: var bgcolor = $('.myclass').first().css('background-color') and then convert it to hex function rgbhex(color) { return "#" + $.map(color.match(/\b(\d+ ...

When serializing a Plain Old Java Object (POJO) in Jersey with JSON, any nested objects will not be

Hello everyone, I am facing a particular issue in the development branch. When I try to serialize a POJO containing a list of nested other POJO using the jersey REST service, the nested POJO is not getting serialized. This problem only occurs in this spec ...

Is it possible to ensure that an asynchronous function runs before the main functional component in React js?

My challenge involves extracting data from an API by manipulating a URL. Specifically, I must retrieve a specific piece of information upon page load and then incorporate it into my URL before fetching the data. var genre_id; var genre; const MOVIE_URL = ` ...

Using jq to arrange JSON objects by their date values

Is there a way to arrange the json output based on the "lastModified" value? I have attempted various approaches using jq but have not been successful. The provided example is just one of several entries. I tried running jq -s '.[].items |= sort_by(. ...

Guide to creating a new window without a menu bar for an onclick function in electronJS

After trying to remove the menu bar from the main window using win.setMenu(null) in the main.js file, I encountered a new issue. When opening a new window (referred to as the "add items window"), I struggled to find a way to hide the menu bar in it as well ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

Tips for refreshing the page upon Geolocation request

I am working on a HTML5 project that requests geolocation from the user. Here is an image of what it looks like: https://i.sstatic.net/o6yCj.png My main query is: Is there a way to refresh the page automatically once the user grants permission to share t ...

A guide on how to parse bash variables into a JSON format

I need help with adding tags to my ec2 instances by passing the key and value via bash variables. #!/bin/bash image="" instancetype=t2.small key1=type value1=test key2=description value2=test123 aws ec2 run-instances --image-id ${image} --count 1 --in ...

The process of removing parent elements and customizing input JSON fields with JOLT specifications

Need assistance with a JOLT spec to remove the _id field, add $date prefix to the date, and eliminate JSON from the input. INPUT: { "JSON":{ "_id":{ "oid":"5f9122213f077e24b639d084" }, ...