Klapsius Klapsius - 11 days ago 6
Javascript Question

jQuery append() not printing table properly

I need to show a

table
on AJAX success and I'm using the
append()
method.
However the end result looks weird because the first row of the table is normal size (full weight of
div
element) and other rows just tiny columns. I think something is wrong with output:

success: function(data) {
var $el = $("#div-right");
$el.empty();
i = 0;
$el.append('<table><tr><td>ID</td><td>Description</td> <td>Status</td><td></td></tr>');

$.each(data, function() {
if (data[i].status == '0') {
statusflag = '<td id="green"> Active </td>';
} else {
statusflag = '<td id="red-b"> Inactive </td>';
}

if (data[i].status == '0') {
action = '<a href="?category-action=' + data[i].id + '&deletetoken=' + data[i].token + '" class="deactivate">'+ '\ <img src="../images/delete.png" width="20" height="20" class="delete">'+ '</a>';
} else {
action = '<a href="?category-action=' + data[i].id + '&deletetoken=' + data[i].token + '" class="activate">'+ '\ <img src="../images/active2.png" width="20" height="20" class="delete">' + '</a>';
}

$el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].id + '</td>\n\<td>' + data[i].description + '</td>' + statusflag + '<td>' + action + '</td></tr>');
i = ++ i;
});

$el.append('</table>');
$("#div-right").show();
},

Answer

As I wrote in the comment, you have to have closing tag of table in the same append... And then append just each tr to $el.find('table'). So change your code to this:

success: function(data) {
    var $el = $("#div-right");
    $el.empty();
    i = 0;
    $el.append('<table><tr><td>ID</td><td>Description</td> <td>Status</td><td></td></tr></table>');

    $.each(data, function() {
        if (data[i].status == '0') {  
            statusflag = '<td id="green"> Active </td>';
        } else {
            statusflag = '<td id="red-b"> Inactive </td>';
        }

        if (data[i].status == '0')  {
            action = '<a href="?category-action=' + data[i].id + '&deletetoken=' + data[i].token + '" class="deactivate">'+ '\ <img src="../images/delete.png" width="20" height="20" class="delete">'+ '</a>';
        } else {
            action = '<a href="?category-action=' + data[i].id + '&deletetoken=' + data[i].token + '" class="activate">'+ '\ <img src="../images/active2.png" width="20" height="20" class="delete">' + '</a>';
        }

        $el.find('table tr:last').after('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].id + '</td>\n\<td>' + data[i].description + '</td>' + statusflag + '<td>' + action + '</td></tr>');
        i = ++ i; 
    });

    $("#div-right").show();  
},

Also you have to use .after to add rows after the last tr.

Comments