Ravi
Ravi

Reputation: 877

Filling form fields from JSON Array with JQuery clone

I have implemented JQuery Clone as in the following link :

http://jsfiddle.net/sunalive/gqQnJ/13/

The same transaction is used for posting and displaying values. I need to display the values from a JSON array (built using PHP from DB) which has values for multiple rows. The JSON Array sample is as below:

 [{"lineNo":"000001","txtLink":"sddf","txtSelect":"2","txtCheck":"X"},
  {"lineNo":"000002","txtLink":"sdfd","txtSelect":"4","txtCheck":""},
  {"lineNo":"000003","txtLink":"frf","txtSelect":"5","txtCheck":"X"}] 

While displaying the same, the row has to clone (as to the number of rows) and values to be shown in the appropriate fields. I will not know the name of the fields or what is coming in the JSON array as everything is generated dynamically at runtime. However, the field names will be of the notation item['fieldname'][] in my form (in the cloned line) where fieldname = key in the JSON array.

I was able to successfully clone rows as below where itemarr holds the JSON array.

  $(itemarr).each(function(index){ 
     $('.gridcontainer').append(emptyItems.clone());

  }

But I have no clue how to display the values into the form fields with dynamic clone.

Can anyone help me achieve this? Thanks for your time and help.

Update: I had found my solution (Thanks Andreas!) and the same is available in the following link:

http://jsfiddle.net/gqQnJ/27/

Upvotes: 0

Views: 689

Answers (1)

Andreas
Andreas

Reputation: 21911

<table id="grid">
    <tr id="emptyItems" style="display:none">
        <td><input type="text" name="item['a'][]" /></td>
        <td><input type="text" name="item['b'][]" /></td>
        <td><input type="text" name="item['c'][]" /></td>
    </tr>
</table>

.

var rows = [
    { "a": 1.1, "b": 1.2, "c": 1.3 },
    { "a": 2.1, "b": 2.2, "c": 2.3 },
    { "a": 3.1, "b": 3.2, "c": 3.3 }
];

$(function() {
    $.each(rows, function(i, row) {
        var newRow = $("#emptyItems").clone().show().appendTo("#grid"),
            inputs = newRow.find("input");

        inputs.each(function() {
            var name = /item\['([^'])'\].*/.exec(this.name)[1];
            this.value = row[name] || "";
        });
    });
});

Example

Upvotes: 1

Related Questions