1

I have a table:

<table id="my-table" border="1">
    <tr>
        <td>Apples</td>
    </tr>
</table>

And I append a row to it as such:

$('#my-table').append('<tr><td>Oranges</td></tr>');

This is a very basic example and a simple append. In my current project the table is a lot larger and making changes are more complicated.

Is there another way to approach this? I mean, if I make a change to my table, I need to go back to my JS file and make a change to the append too. Seems a little redundant. This might be a ridiculous question but I'm curious to know if there's a simplified approach.

SeanWM
  • 16,789
  • 7
  • 51
  • 83

3 Answers3

2
  1. Use client templating. I prefer handlebars. So you got a template like

    <script id="table-row-template" type="text/x-handlebars-template">
        <tr><td>{{name}}</td><td>{{second_name}}</td><td>{{age}}</td></tr>
    </script>
    

    somewhere included in your page.

  2. Get data from server using AJAX and use the template:

    $.ajax({
        url: 'mysite.com/tableRowData',
        dataType: 'json',
        success: function(response) {
            var source   = $("#table-row-template").html();
            var template = Handlebars.compile(source);
            $('#myTable tbody').append(template(response)); // Notice tbody.
        }
    });
    

This way you can keep your templates for each table in different files wher you keep inly HandleBars template. This approach frees you to use this ugly syntax when you write HTML in append method, because sometimes it's quite hard to read, like

      $('#myTable tbody').append('<tr><td><span class="..">...</span></td><td><img src="..."><span class="...">...</span></td>....</tr>');

Moreover, since you retrive only JSON data from server it's possible to make several designs of your app

Victor
  • 5,073
  • 15
  • 68
  • 120
  • Why ajax ? Just store the template hidden in the page get it it using js. – Virus721 Sep 18 '13 at 13:31
  • 1
    @Virus721 - check the code again and rethink your comment. – N.B. Sep 18 '13 at 13:39
  • And what about the current data I already have in the database? How would I handle that and put it into the template from a PHP array? This process is great as I add it through ajax. – SeanWM Sep 18 '13 at 13:41
  • Mmm yeah... However i don't like this philosophy of adding a whole framework everytime you need to add something when it can be done in a simpler way. – Virus721 Sep 18 '13 at 13:42
  • @Victor Is it possible to use client side templating with a current table being generated by a PHP loop (its rows are being looped out from data in a PHP array)? – SeanWM Oct 31 '13 at 14:17
  • Not sure I understood your question. You can generate a table by PHP loop, and then work with it with javascript using templates, there is no problem. But if you want to show, for example, a user list, and want to have buttons like "prev" and "next" to navigate the list, and you want to generate first page of user list in PHP, it's not a good idea since you may as well retrive first page by AJAX too.. but anyway you may work with already generated table – Victor Oct 31 '13 at 16:20
  • So I've been doing a lot of research and went with handlebars.js myself. I guess there's no way around having the entire table in the template? Rather than just the ? I guess it won't work because I want to append more rows to that table after the initial table render. – SeanWM Nov 04 '13 at 02:54
  • You may use entire table in handlebars, just use {{#each}} cycle inside to loop through rows. And you'll still have tag in handlebars template. If you want to append something, get rows using handlebars, then $('#table tbody').append(items_got_by_using_handlebars_template)
    – Victor Nov 04 '13 at 05:42
0
$rowTpl  = $( '#row-tpl' );
$myTable = $( '#my-table' );

for( ... ) {

    var param1 = ... ,
        param2 = ... ,
        // Etc...

    $rowTpl.html( $rowTpl.html()
        .replace( '{{ param1 }}', param1 )
        .replace( '{{ param2 }}', param2 )
        // Etc...
    );

    $myTable.append( $rowTpl );
}
Virus721
  • 8,061
  • 12
  • 67
  • 123
0

There are a lot of subtle concepts around appending rows to a large table because performance becomes an issue very quickly. Some best practices evolve as new versions of the browsers are released.

There are several valuable benchmark comparisons of various techniques you can review: http://jsperf.com/append-table-rows/2, http://jsperf.com/building-a-big-table.

Creating a template to clone, as j08691 suggests above, perhaps by cloning an existing row in your case, will definitely help keep your script concise, and is demonstrably faster than some other methods as shown in the second link above.

Another concept to consider is fixing your column widths early to prevent reflows (When does reflow happen in a DOM environment?).

Libraries and widgets offer convenient methods for this as well as more complex and powerful performance enhancing options such as scroll-to-load in jQuery Datatables (http://datatables.net/extras/scroller/).

Community
  • 1
  • 1
cage rattler
  • 1,587
  • 10
  • 16
  • Nothing about using templates? I like the idea of cloning a row and updating values though. It seems like the fastest and cleanest way out of the options you gave. – SeanWM Sep 18 '13 at 13:58
  • Sean, I was just trying to consider best practices for performance and concise code. Knowing only what you have presented above, I don't feel I could weigh in on the possible use of a templating engine. If it would be useful in other contexts in your project, then that would make great sense though. – cage rattler Sep 18 '13 at 14:11