Search code examples
jqueryjsonnested-loops

Looping through json to create table


Maybe I'm doing this a bad way, but I was trying to loop through the json to create a table. Coding it without the loop works and I can loop through with one loop but if I add a nested one it doesn't create rows. Am I doing this right or am I missing something?

for(var i = 3; i < 17; i++){

   $('.one').append("<tr>");

   for(var j = 0; j < 5; j++){

       $('.one').append("<td>" + obj.values[i][j] + "</td>" );    

    }

    $('.one').append("</tr>");
}

I hope it's not a simple typo I'm overlooking but I've several ways and can get it to work by hard coding j and making the line longer. I'm still pretty new and this was my first successful ajax call. Any help is greatly appreciated. Thank you.


Solution

  • JQuery .append() does not append individual open and closing tags to the DOM. It appends a whole element - open and closing tag. In your code, each time you call append(), it's overwriting the previous ouput.

    Here's a possible solution:

    for(var i = 3; i < 17; i++){

    $('.one').append("<tr>");
    
    for(var j = 0; j < 5; j++){
    
        $('.one tr').html("<td>" + obj.values[i][j] + "</td>");    
    
     }
    

    }