Bogdan Bogdanov
Bogdan Bogdanov

Reputation: 386

td's in table creating with jquery without html

Here is my jsfiddle work. I have some issues with generating table without any html. I have one json object that i need to itterate and to put keys and values in table like:

<tr> <td> key </td> <td> key </td> ... </tr>
<tr> <td> val </td> <td> val </td> ... </tr>

I tried first to generate the table like this one, but next i wanted to use jquery version of creating td's and tr's, but the all keys and values were appended in only one td and actually this is not what i want.

Upvotes: 2

Views: 136

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You have to loop through keys the first time to set the head of table, after that make the rows inside each and append every one to the table to make the body of your table, check example code bellow :

$.ajax({
    type : "POST",
    dataType : "json",
    url : '/echo/json/',
    data : { json: JSON.stringify( jsonData ) },
    success : function(data){
        var jsn = $(data.markers);

        //First time append table head
        if(!header)
        { 
            var row = $('<tr></tr>');

            for(key in jsn[0])
            {
                row.append('<th>'+key+'</th>');
            }

            table.append(row);

            header = true;
        }

        for ( var i = 0; i < jsn.length ; i++){
            var row = $('<tr></tr>');

            $.each(jsn[i], function(key,val)
            {
                row.append('<td>'+val+'</td>');
            });

            table.append(row);
        }

    }        
});

Take a look at Working fiddle.

Hope this helps.

Upvotes: 1

dfsq
dfsq

Reputation: 193301

You need to create new row object in each for iteration:

for (var mrksIndex = 0, mrksLength = jsn.length; mrksIndex <= mrksLength; ++mrksIndex) {
    row = $("<tr/>");
    $.each(jsn[mrksIndex], function (key, val) {
        col = $("<td/>");
        col.append(key);
        row.append(col);
        table.append(row);
    });
}

Demo: https://jsfiddle.net/6dw2u8uz/15/

Upvotes: 1

Iulian Cravet
Iulian Cravet

Reputation: 389

The issue was in the scope of the col and row variables. You must reassign them in the loop, or redeclare. Here is the updated jsfiddle. By the way there is no need to use for loop. In jQuery it is enough to use the $.each function on the object.

From here you can see how to create table structure and replace the key and val with the actual data you need.

Upvotes: 1

Related Questions