V
V
Vitaly2015-09-25 12:21:36
css
Vitaly, 2015-09-25 12:21:36

How to create an HTML table with javascript?

I'm trying to create a table in jquery with data received from the server in json format

var a = ['id', 'user_id', 'result', 'date_time']

 var trHTML = '';
            $.each(response, function (i, x) {
                trHTML += '<tr><td>' + x['id'] + '</td><td>' + x['user_id'] + '</td><td>' + x['result'] + '</td><td>'+x['date_time']+'</td></tr>';
            });
            $('table').append(trHTML);

How can I make this code so that I do not write manually? Since the number of td can be different, but take their number and data from var a ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Tolerant, 2015-09-25
@Scorpiored88

var response = [{
    id: 1,
    user_id: 2,
    result: 'test',
    date_time: '123'
}],
    trHTML = '';

$.each(response, function (i, x) {
    trHTML += '<tr>'
    for (res in x) {
        trHTML += '<td>' + x[res] + '</td>';
    }
    trHTML += '</tr>';
});
$('table').append(trHTML);

https://jsfiddle.net/s25nt4na/1/

G
Gregory, 2015-09-25
@grigruss

trHTML+='<tr>';
$.each(x,function(k,v){
    trHTML+='<td>'+v+'</td>';
});
trHTML+='</tr>';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question