最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Loop through rows to get value of dynamically generated inputs - Stack Overflow

programmeradmin1浏览0评论

I am using PHP, JSP and JSON for this code. I have to get values of my textboxes so I can insert them into my database.

I have a table that holds a siblings information, of course we have differrent number of siblings so I created a table that dynamically adds row and columns with textboxes on button click.

Here is the HTML code for 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>

And he script that dynamically adds row and columns with textboxes:

<script type="text/javascript">
    //Dynamically create rows and columns 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 give each input an id by:

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

Now I need to get each value so I can pass them on PHP page and insert each on the database.

But it only gets the first row, I get the last row so I can determine the number of rows. and created an array so I can just push the values from it.

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

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

Now my problem is this line:

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

How can I get each value of textbox from a dynamically created rows and columns??

Anyone?PLEASE HELP! THANKS A LOT.

I am using PHP, JSP and JSON for this code. I have to get values of my textboxes so I can insert them into my database.

I have a table that holds a siblings information, of course we have differrent number of siblings so I created a table that dynamically adds row and columns with textboxes on button click.

Here is the HTML code for 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>

And he script that dynamically adds row and columns with textboxes:

<script type="text/javascript">
    //Dynamically create rows and columns 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 give each input an id by:

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

Now I need to get each value so I can pass them on PHP page and insert each on the database.

But it only gets the first row, I get the last row so I can determine the number of rows. and created an array so I can just push the values from it.

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

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

Now my problem is this line:

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

How can I get each value of textbox from a dynamically created rows and columns??

Anyone?PLEASE HELP! THANKS A LOT.

Share Improve this question edited Jul 30, 2013 at 4:24 omma2289 54.7k8 gold badges66 silver badges68 bronze badges asked Jul 30, 2013 at 3:06 QKWSQKWS 1,1099 gold badges22 silver badges41 bronze badges 9
  • Why not give them a class so you can use $(".classname").each()? – Barmar Commented Jul 30, 2013 at 3:09
  • an easier way would be to use jQuery's serialization just give your inputs descriptive names and use [] to define each as an array, i.e: siblings[0][name] – omma2289 Commented Jul 30, 2013 at 3:12
  • @koala_dev, How can I accessed each row then? – QKWS Commented Jul 30, 2013 at 3:15
  • you need to traverse the columns also right? or are you looking to extract only the value of input field with id txtSib10? – Harry Commented Jul 30, 2013 at 3:22
  • You have multiple 'td's (inputs) in a row, but you're looping through rows, shouldn't you be looping through columns of each row instead? – Samurai Commented Jul 30, 2013 at 3:26
 |  Show 4 more ments

3 Answers 3

Reset to default 5

This is how I normally handle this type of dynamically generated rows of inputs. I start with my form and name all my inputs as a single multi-dimensional array, with an index (starting with 0) and the name of the data they represent, in your case something like siblings[0][name] for your first input:

HTML

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

Now to add a new row, I duplicate the last one in the table and clear all the input values and update the index in their name attribute, something like:

JS

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

In your case it looks like you're using ajax to send the data to your server so I would use jQuery's $.post() like this:

$.post('myphpfile.php',$('#tbSibling :input').serialize());

Now in your PHP you would have all your data in an array under $_POST['siblings'] that you can loop and store in your database

PHP

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

shouldn't it be like :

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

$("#txtSib10").val()

ID's are unique: https://developer.mozilla/en-US/docs/Web/API/element.id

"The ID must be unique in a document, and is often used to retrieve the element using getElementById."

Change your script that generates the markup to use a class name, then grab the value for each generated text box within a loop.

Since the object you are building contains data for name, age, phone number and occupation, I would remend adding a class name to each row, looping over that, then building 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()+'"}';
});

Assign a class name that can be used for the text fields in every row so that when looping over them the same code can be used:

<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>
发布评论

评论列表(0)

  1. 暂无评论