MrTechie
MrTechie

Reputation: 1847

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);

    },

Upvotes: 0

Views: 253

Answers (1)

Marek Koziorowski
Marek Koziorowski

Reputation: 277

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);

},

Upvotes: 1

Related Questions