0

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

    },
5
  • What are you trying to split into columns? How do you want it to look? At the risk of sounding condescending, html "columns" are "td" and rows are "tr" ... a 2 column row has the format <tr><td>stuff</td><td>stuff</td></tr> Commented Oct 23, 2016 at 16:21
  • I understand what rows and columns are in html. I want it to tr, td, td, /tr and rinse and repeat. Commented Oct 23, 2016 at 16:25
  • Note: you need to get var v = 0; out of $.each(...) Commented Oct 23, 2016 at 16:26
  • Not really, because each time it loops over a new piece of data from the json, it has to set the val to be 0 to count whether td is 1 or 2 Commented Oct 23, 2016 at 16:29
  • So v === 0 all the time Commented Oct 23, 2016 at 16:32

1 Answer 1

1

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

},
Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! Works like a charm. Thanks for chiming in Marek. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.