JSON Structure:
{“rows”: [
{"row":[ {"cells": [ {"data": "Edit"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Add"}, {"data": "030194"}, ]} ]}, {"row":[ {"cells": [ {"data": "Delete"}, {"data": "030194"}, ]} ]}]}
JQuery code:
$.each(response.rows, function(index, rows){
$.each(rows.row, function(index,row){ var element=$("tbody").append("<tr id='" + index + "'>"); var element1=element.append("<td><input type='checkbox'></input></td>"); $.each(this.cells, function(index){ element1.append("<td>" + this.data + "</td>"); }); $("tbody").append("</tr>"); });});
Problems:
-
Each row generated has an ID with value of index = 0. The ID for Row1 should be 0, for Row2 it should be 1 and for Row3 ID should be equal to 2
-
td elements are drawn out as children of tbody. They should be children of tr
-
closing tr should be drawn after the last cell in each row, currently the tr closes itself before any cell is drawn
Try this. This stumped me for a bit, because I was used to the syntax of .each() in the context of looping through DOM elements. Since it’s $.each(), the index of the first loop refers to the number you were trying to get for every row.
I moved the TR append outside the loop you had it in.
(Last-child isn’t the fastest method of adding the TDs, you could use createElement like Endophage posted, and then refer to that)
http://jsfiddle.net/EY4an/
I also added the word ‘index’ to the ID attributes on the table rows, because IDs are supposed to start with a letter.