By | August 3, 2017

To start we need to get the our test table and empty the contents as shown below:

1
2
var table = $("#TestTable");
table.find('tbody').empty(); //Empty the contents before populating again

Here is one way to build up the tables contents, using the concatenated string method:

1
2
3
4
5
6
7
8
9
for(var i = 0; i < products.length; i++){
   var row = '<tr>';
   row = row + '<td>' + products[i].Id+ '</td>';
   row = row + '<td>' + products[i].Name+ '</td>';   
....         
   row = row + '<td>' + products[i].Status + '</td>';
   row = row + '</tr>';
   table.find('tbody').append(row);
}

But there are few drawbacks of writing such code:

  1. There is a need to keep a track of all the closing tags.
  2. The more complex the logic, the messier and less maintainable the code becomes.

So here is a more elegant way of writing the same code, where each HTML tag is added separately to its parent element. To make it simple, start with the lowest node and move upwards building its parent recursively.

Lets consider a list of objects, say “Products”, that need to be populate our table on the fly. Each of the Product object maps to a row in a HTML table:

1
2
3
4
5
6
7
8
for(var i = 0; i < products.length; i++){               
    var row =  $('<tr/>', {class: '' });
    row.append($('<td/>').append(products[i].Id));
    row.append($('<td/>').append(products[i].Name));
....
    row.append($('<td/>').append(products[i].Status));
    table.find('tbody').append(row);
}

The above is only a simple example. There could be much more complex HTML tags that could be added in similar way.

Leave a Reply

Your email address will not be published. Required fields are marked *