Question

We can convert a set of JSON data to html table by below code:

$.each(data, function(key, val) {
    var tr=$('<tr></tr>');
    $.each(val, function(k, v){
        $('<td>'+v+'</td>').appendTo(tr);
    });
    tr.appendTo('#display');
});

The html table is:

<table border='1' id="display">

    <thead>
            <tr>
                <th>firstcol</th>
                <th>loc</th>
                <th>lastA</th>
                <th>mTime</th>
                <th>nTime</th>
                <th>Age</th>
                <th>ction</th>
            </tr>
        </thead>        
</table>

A working example at: http://jsfiddle.net/AHv6c/ (source jquery code to display json response to a html table using append)

My problem is when some of the rows columns could have their own style class.

So I want to change some of the the table <th> to <th class='sampleStyle'> . Can you please let me know how should I change the java script to read the corresponding class from th and assign it to relevant columns (s).

Then the generated table should be something like:

<tr>
     <td>56036</td>
     <td class="sampleStyle">Deli</td>
     ....

By the way do you know better approach?

Was it helpful?

Solution

You may try something like http://www.jqversion.com/#!/Mdi8Kla

$.each(data, function(key, val) {
    var tr    = $('<tr></tr>'),
        index = 0;
    $.each(val, function(k, v){
        $('<td>'+v+'</td>').addClass(
          $('th:eq(' + index + ')').attr('class')
        ).appendTo(tr);
        index++;
    });
    tr.appendTo('#display');
});

OTHER TIPS

$("td:eq(0)", tr).addClass("sampleStyle");

before appending tr

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top