Reputation: 3489
I want to to concatenate the results of a jquery each
loop inside of another but am not getting the results I expect.
$.each(data, function () {
counter++;
var i = 0;
var singlebar;
var that = this;
tableRow = '<tr>' +
'<td>' + this.foo + '</td>' + //<---- should terminate this instead
$.each(this.bar, function(){
singlebar = '<td>' + that.bar[i].baz + '</td>';
tableRow += singlebar;
console.log(singlebar); // outputs "<td>the correct data</td>"
});
'</tr>';
$(tableRow).appendTo('#mainTable > tbody');
});
The portion inside the nested each
does not get added to the string that is returned.
I can console.log(singlebar)
and get the expected results in the console but I cannot concatenate those results inside the primary each
loop.
I have also tried:
$.each(this.bar, function(){
tableRow += '<td>' + that.bar[i].baz + '</td>';
});
Which also does not add the desired content.
How do I iterate over this nested data and add it in the midst of the table that the primary each
statement is building?
The solution (thanks to sushanth reddy)
I should not have continued trying to concatenate in such a way. I should have added each section of string to tableRow
as I created it, not all at once. Something more like:
tableRow = '<tr>' +
'<td>' + this.foo + '</td>';
$.each(this.bar, function(){
singlebar = '<td>' + that.bar[i].baz + '</td>';
tableRow += singlebar;
});
tableRow += '</tr>';
Upvotes: 2
Views: 845
Reputation: 55750
You are returning at the wrong point.. Try this
var counter = 0;
var tableRow = '';
$.each(data, function () {
counter++;
var i = 0;
var singlebar;
var that = this;
tableRow = '<tr>' +
'<td>' + this.foo + '</td>' +
$.each(this.bar, function(){
singlebar = '<td>' + that.bar[i].baz + '</td>';
tableRow += singlebar;
});
tableRow += '</tr>';
$(tableRow).appendTo('#mainTable tbody');
});
Check this example FIDDLE
Also make sure you have the table and tbody tags before you append..
Upvotes: 2
Reputation: 116
$.each(data, function () {
counter++;
var i = 0;
var singlebar;
var that = this;
var tableRow = '<tr>' +
'<td>' + this.foo + '</td>';
$.each(this.bar, function(){
singlebar = '<td>' + that.bar[i].baz + '</td>';
tableRow = tableRow + singlebar;
});
tableRow = tableRow + '</tr>';
return tableRow;
});
Upvotes: 0
Reputation: 1972
Try this
$.each(data, function () {
counter++;
var i = 0;
var singlebar;
var that = this;
tableRow = '<tr>' +
'<td>' + this.foo + '</td>';
$.each(this.bar, function(){
singlebar = '<td>' + that.bar[i].baz + '</td>';
tableRow = tableRow + singlebar;
});
tableRow = tableRow + '</tr>';
});
return tableRow;
Upvotes: 0