Dip
Dip

Reputation: 143

Jquery .html() adds only one row to the table

I am using append() to add new rows to the table, but the problem is that I need to remove the old rows before adding new.

success: function(response) {
    response.AnArray.forEach( function (arrayItem){
        $('.tableName > tbody').append('<tr>...</tr>');
    });
}

Then I switched to html() over append(), now that adds only one row to the table.

Note :

$('.tableName > tbody').empty();

Is not working in my case.

What am I missing?

Upvotes: 0

Views: 297

Answers (4)

Gammer
Gammer

Reputation: 5608

My solution is similar to @Shree, But use html() there instead of append.

success: function(response) {
    $('.createPOVTable > tbody').empty();
    var htmlData = '';
    response.AnArray.forEach( function (arrayItem){
      htmlData += '<tr>...</tr>';
    });
    $('.createPOVTable > tbody').html(htmlData)
} 

Upvotes: 1

4b0
4b0

Reputation: 22323

Don't use append in every loop so first generate mark up as a string and append ones out side the loop like this.

success: function(response) {
    $('.createPOVTable > tbody').empty();
    var html = '';
    response.AnArray.forEach( function (arrayItem){
      html += '<tr>...</tr>';
    });
    $('.createPOVTable > tbody').append(html)
}

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 10148

Well, if you want to remove all the previous rows, what you can do is

$("#tbodyID").empty();

This will clear the table body and then use

$("#tbodyID").append('<tr>...</tr>');

So, your final code should look like

success: function(response) {
   $("#tbodyID").empty();
response.AnArray.forEach( function (arrayItem){
    $("#tbodyID").append('<tr>...</tr>');
});
}

Upvotes: 1

beliha
beliha

Reputation: 322

.html() completely replaces the contents of the tbody on each iteration, so it will always just show the last row inserted. Instead, empty out the tbody before you start the iteration, then use append to add the new row, as below:

success: function(response) {
    $('.createPOVTable > tbody').empty();
    response.AnArray.forEach( function (arrayItem){
        $('.createPOVTable > tbody').append('<tr>...</tr>');
    });
}

Upvotes: 4

Related Questions