Generating HTML Tables with jQuery

4 במרץ 2009

תגיות: , , , ,
18 תגובות

Shlomo has shared with us  in his post a trick that can be used to pass parameters to event handlers. The trick is based on the fact that every HTML element can have unlimited custom attributes, therefore, using element's  setAttribute() method it is possible to append any attribute you can imagine. Shlomo also shows us one of the possible ways of dynamically creating rows in HTML table using browser’s DOM, and attaching events to elements .

One drawback with this trick is that is breaks HTML 4 compatibility of the web page. While in most cases this is not an issue, in general we should always prefer not to break compatibility if possible.

Following that, I’d like to demonstrate another way of achieving the same result without breaking compatibility, using jQuery library. The library provides a fast, clean and cross-browser development experience.

We will start with creating a basic HTML markup for our page. The following already includes a reference to jQuery library, and a definition for a CSS class we’ll use for generated table cells. I’m using the recently released jQuery  version 1.3.2 with Visual Studio annotations, which provide a nice intellisense experience inside VS 2008. For production deployment, the reference should be changed to a minified version of jQuery. For more information about jQuery intellisense support in VS 2008, please read ScottGu’s blog post.

  1: <html xmlns="http://www.w3.org/1999/xhtml">
  2: <head>
  3:     <title>Dynamic HTML Table Creation with jQuery</title>
  4: 
  5:     <script src="jquery-1.3.2-vsdoc.js" type="text/javascript">
  6:     </script>
  7: 
  8:     <style type="text/css">
  9:         td.tableCell
 10:         {
 11:             padding: 5px;
 12:         }
 13:     </style>
 14: </head>
 15: <body>
 16:     <table id="tbl" border="1">
 17:         <tbody>
 18:         </tbody>
 19:     </table>
 20: </body>
 21: </html>

The second step is to write a function that dynamically generates rows for HTML table:

  1: <script type="text/javascript">
  2:     function createDynamicTable(tbody, rows, cols) {
  3:         if (tbody == null || tbody.length < 1) return;
  4:         for (var r = 1; r <= rows; r++) {
  5:             var trow = $("<tr>");
  6:             for (var c = 1; c <= cols; c++) {
  7:                 var cellText = "Cell " + r + "." + c
  8:                 $("<td>")
  9:                         .addClass("tableCell")
 10:                         .text(cellText)
 11:                         .data("col", c)
 12:                         .appendTo(trow);
 13:             }
 14:             trow.appendTo(tbody);
 15:         }
 16:     }   
 17: </script>

The createDynamicTable() function accepts three arguments: the jQuery object representing the table and desired number of rows and columns in the table. On line 3 the function performs input validation for the table reference argument. In general, jQuery selection returns an array of elements, so if nothing was selected, the length property will contain a zero value.

The function then loops through rows and columns generating table rows and table cells. Line 5 demonstrates the simples way to create any HTML element, and in particular, a table row. Lines 8 through 12 are actually one splitted line. One of the most recognized qualities of jQuery is functions chainability, or the fluent interface it provides, so every function actually returns a modified jQuery object that can be further modified by the next chained function call. So line 8 creates a new table cell, line 9 appends a CSS class to that cell (the class was defined in a header of the HTML), line 10 sets the inner text of the cell.Line 11 sets a column number into element’s data (I’ll elaborate on that in a moment), and line 12 appends the current element (table cell) to the table row created above. Finally, line 14 appends the table row to the table itself – jQuery will append the row to the <tbody> element of the table.

Now, as for the data function. jQuery can store any data we want for any element on our page. Think of it as an array of properties (a hash table to be more precise), attached to an element. Internally, jQuery manages cache object, which is a hash table itself, where it can save any data it wants for any element. It is possible to achieve the very same by declaring a new array, and setting a unique ID for every element on our page, but why bother? jQuery makes our life easy.

The next step is to call that function. I want the table to be generated as soon as possible. The $(document).ready() event is the most appropriate candidate for that purpose:

  1: $(document).ready(function() {
  2:     createDynamicTable($("#tbl"), 10, 5);
  3: });

In the script above, I’ve attached an anonymous function to the ready event of the current document. The ready event is fired as soon as the DOM is ready for manipulations, before loading images and other external resources. I’m calling the createDynamicTable function passing the table with id=”tbl” – the is what the $(“#tbl”) selector does. The function supposed to create 10 rows with 5 cells in each. Something like that:

image

Now, the last step for this sample is to react to the click event of each cell alerting with the column number. It can be achieved by adding a single line of script (well, a splitted one) into the $(document).ready handler. This is the modified handler:

  1: $(document).ready(function() {
  2:     createDynamicTable($("#tbl"), 10, 5);
  3:     $("#tbl td.tableCell")
  4:             .click(function() {
  5:                 alert("Clicked Col=" + $(this).data("col"));
  6:             });
  7: });

On line 3 I’m selecting every table cell element which is a child of an element with id=”tbl”, and includes a CSS class “tableCell”. For this sample, the same effect could be achieved by selecting all the table cells: $(“td”), or by selecting all the elements with class “tableCell”: $(“.tableCell”). All of the selectors above will result the same collection of elements – the table cell we’ve created before.

Following the selection, on line 4, an anonymous function is attached to the "click” event of every selected element (every table cell). jQuery’s event handler functions run in the context of the attached DOM element, therefore, the this variable inside the function holds a reference to a DOM element representing our cell. To get the data stored for the element, the element must first be selected and converted into jQuery object. This is achieved by the $(this) construct following the call to a data(“col”) function that will return the column number for the clicked cell (we have stored it in the createDynamicTable) function.

That’s all, folks. Now every cell click will result an alert:

image

Pretty straight-forward in my opinion. Write me if you have questions and/or suggestions.

UPDATE: You can download the source code for this from my SkyDrive:

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

18 תגובות

  1. Shlomo4 במרץ 2009 ב 13:07

    פוסט יפה מאוד.
    תודה רבה

    להגיב
  2. Josh Powell4 במרץ 2009 ב 18:58

    This is very slow:

    for (var r = 1; r < = rows; r++) {
    var trow = $("
    ");
    for (var c = 1; c < = cols; c++) {
    var cellText = "Cell " + r + "." + c

    $(" ")
    .addClass("tableCell")
    .text(cellText)
    .data("col", c)
    .appendTo(trow);
    }
    trow.appendTo(tbody);
    }

    Much faster:
    var html = '
    ';
    for (var r = 1; r < = rows; r++) {
    html += '
    ' + cellText + '

    ';
    };
    html += '

    ';
    $('table').append(html);

    To see why, go to http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

    Excellent work on the event handlers, using .click to iterate over the list and $(this) inside. I think that is exactly the way to do it. Check out .live which is new to jquery 1.3 for another way.

    להגיב
  3. linqed4 במרץ 2009 ב 20:33

    Thanks for your comment, Josh.
    I'm fully aware of the performance of the append function. However, I wanted to demonstrate the chainability effect of jQuery, and various functions.
    Your code is much much faster, I agree, but mine is greater for demo :) I might add an update explaining this in the post.

    As for the "live" event, I've used it too in my work. But I tend not to use it in case I don't need it. Just take a look at the code of the jQuery to understand why.

    Vlad

    להגיב
  4. Wilver Adolfo Gonzalez A.11 במרץ 2009 ב 17:57

    Thanks Vlad.
    Your example is Great!
    and so good explained.

    להגיב
  5. Anonymous10 ביולי 2009 ב 3:40

    I should say that blogs.microsoft.co.il has lots of interesting information. Looks like the author did a good job. I will be coming back to blogs.microsoft.co.il for new information. Thank you.

    להגיב
  6. James19 ביולי 2009 ב 17:51

    Thanks for share this.
    This make us easy to create a html table through jquery

    להגיב
  7. custom writer5 ביולי 2012 ב 16:18

    The code has been of great help to me. Thank you for sharing

    להגיב
  8. zaheer30 ביולי 2012 ב 14:17

    how to connect the html table to sql then how to perform the crud application using jquery????

    להגיב
  9. Stclair30 במרץ 2013 ב 8:49

    green coffee men's underclothes can and reshapes curves4. Dr. Oz explained that a 30 day cater of Green Coffee Dome extract will cost preoccupied all this metre made Alexis's bosom ache.
    When nerveless add the effectiveness of anticoagulant drugs
    such as warfarin or Coumadin victimized to process and forbid roue clots.
    through and through out forfend situations that will
    induce you eat things that you shouldn't eat.

    להגיב
  10. uvlapuvr8 בספטמבר 2013 ב 22:01

    liquidation
    anthology
    [url=http://www.basalpro.com/chaneloutlet.html]Chanel Bags[/url]
    strip-mine
    clamp
    [url=http://www.wobart.com/louisvuittonoutlet.html]Louis Vuitton Outlet Online[/url]
    maximum
    abbreviation
    [url=http://tawabook.com/lancel.html]Lancel pas cher[/url]

    להגיב
  11. Supreme Cap9 בספטמבר 2013 ב 8:44

    Hi! Would you mind if I share your blog with my twitter group? There's a lot of folks that I think would really enjoy your content. Please let me know. Thanks
    Supreme Cap

    להגיב
  12. wppzpvkhfd10 בספטמבר 2013 ב 3:21

    [url=http://www.gl248amc9mv0ex15r5m18863oq36g6pas.org/]uwppzpvkhfd[/url]
    awppzpvkhfd
    wppzpvkhfd http://www.gl248amc9mv0ex15r5m18863oq36g6pas.org/

    להגיב
  13. dimdnwejs10 בספטמבר 2013 ב 13:12

    adimdnwejs
    [url=http://www.g82fjh1g9f097706v8jv09s2eliy8a8xs.org/]udimdnwejs[/url]
    dimdnwejs http://www.g82fjh1g9f097706v8jv09s2eliy8a8xs.org/

    להגיב
  14. セイコー 時計10 בספטמבר 2013 ב 13:52

    It's a pity you don't have a donate button! I'd most certainly donate to this superb blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with my Facebook group. Chat soon!
    セイコー 時計 http://www.seiktokei.com/

    להגיב
  15. edjgxrp10 בספטמבר 2013 ב 15:07

    edjgxrp http://www.g3iw24h032b2186e5b7f6farcq0e4ms1s.org/
    [url=http://www.g3iw24h032b2186e5b7f6farcq0e4ms1s.org/]uedjgxrp[/url]
    aedjgxrp

    להגיב
  16. iewiyem12 בספטמבר 2013 ב 2:13

    aiewiyem
    iewiyem http://www.g533pw36rqxt43fwm75xg156tf583w7xs.org/
    [url=http://www.g533pw36rqxt43fwm75xg156tf583w7xs.org/]uiewiyem[/url]

    להגיב
  17. vrtpnou@gmail.com12 בספטמבר 2013 ב 3:24

    YBcZqVRl
    YBcZqVRl http://www.9IQOf25T8C88Q4ZK8L8syW.com/
    [url=http://www.9IQOf25T8C88Q4ZK8L8syW.com/]YBcZqVRl[/url]

    להגיב