简体   繁体   中英

How to get the values from dynamically created row of textboxes in JSON

I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.

I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.

<table id="myTable">
    <th>Name</th>
    <th>Age</th>
    <th>Gender</th>
    <th>Occupation and Employer</th>
    <th>Add</th>
    <tr>
        <td><input type="text" id="txtName" /></td>
        <td><input type="text" id="txtAge" /></td>
        <td><input type="text" id="txtGender" /></td>
        <td><input type="text" id="txtOccupation" /></td>
        <td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
        <td><input type="button" id="btnSave" class="button-add" value="Save"></input>  </td>
    </tr>
</table>

<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;   
}


$(document).ready(function(){
$("#btnsave").click(function ()
{          

alert("Hi");
var dataToSend={
          'Name':[],
           'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
                          dataToSend.Age.push({$("txtAge").val().trim()});
                          localStorage.setItem('DataToSend', JSON.stringify(DataToSend));

var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));

// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);

alert(restoredSession);

    });
});

JSFIddle: http://jsfiddle.net/S7c88/

Since you are using jQuery you can greatly simplify the whole process by using methods like clone() .

Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name .

var $row;

function insertRow() {
    $('#myTable').append($row.clone());
}
$(function () {
    $row = $('tr').eq(1).clone();  /* clone first row for re-use*/   
    $('#myTable').on('click', '.btnSave', function () {
        var dataToSend = [];
        $('tr:gt(0)').each(function () {
            var data = {};
            $(this).find('input').each(function () {
                data[$(this).data('name')] = this.value
            });
            dataToSend.push(data);
        });      
        /* display data in textarea*/
        $('#output').val(JSON.stringify(dataToSend, null, '\t'))
    });
}) ;

I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons

Your demo has invalid html, missing <tr> for top set of <th>

DEMO

Some areas where you were going wrong:

  • $("txtName") Invalid selector
  • No row references in attempt to gather data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM