MrTechie MrTechie - 1 month ago 8
Javascript Question

How to have jquery loop over json data results to create a two column table

I'm having a bit of trouble trying to get my json data response shown in a two column table. I've found lots of posts that show how to show it as a single row, but nothing as a two column table.

This is what I have so far and it is still only showing a single column with multiple rows:

var trHTML = '';

$.each(data.Titles, function (i, item) {
var v = 0;


trHTML += '<tr>';

if(v <= 2){
trHTML += '<td><a href="' + data.Links[i] + '">' + data.Titles[i] + '</a><br><img src="' + data.Images[i] + '"></td>';
}
else{
var v = 0;
trHTML += '</tr>';
trHTML += '<tr>';
}

trHTML += '</tr>';
v++
});

$('#location').append(trHTML);

},

Answer

Try this:

var trHTML = '';
var v = 0;

$.each(data.Titles, function (i, item) {        

    // it keeps v always 0 or 1 regarding if it's first or second column
    if(v >= 2){
        v = 0;
    }

    if(v == 0){
        trHTML += '<tr>';
    }

    trHTML += '<td><a href="' + data.Links[i] + '">' + data.Titles[i] + '</a><br><img src="' + data.Images[i] + '"></td>';

    if(v == 1){
        trHTML += '</tr>';
    }

    v++
});

if(v == 1){
    trHTML += '</tr>';
}

$('#location').append(trHTML);

},
Comments