[ Team LiB ] Previous Section Next Section

14.7 Transforming JavaScript Objects into HTML Tables

NN 6, IE 5(Win)

14.7.1 Problem

You want to render embedded JavaScript data as an HTML table.

14.7.2 Solution

When JavaScript data is formatted as an array of objects, it is a relatively simple job to use the data to drive the creation of rows and cells of an HTML table. Here is an example of some repetitive data assembled on the server as a JavaScript array (perhaps from a database query):

// Table data -- an array of objects
var jsData = new Array( );
jsData[0] = {location:"Uruguay", year:1930, winner:"Uruguay", winScore:4, 
             loser:"Argentina", losScore:2};
jsData[1] = {location:"Italy", year:1934, winner:"Italy", winScore:2, 
             loser:"Czechoslovakia", losScore:1};
jsData[2] = {location:"France", year:1938, winner:"Italy", winScore:4, 
             loser:"Hungary", losScore:2};
jsData[3] = {location:"Brazil", year:1950, winner:"Uruguay", winScore:2, 
             loser:"Brazil", losScore:1};
jsData[4] = {location:"Switzerland", year:1954, winner:"West Germany", winScore:3, 
             loser:"Hungary", losScore:2};

A skeleton of the table is delivered with the HTML, so that the column headings are already in place, and a table body section is set to receive the dynamically created table content:

<table id="cupFinals">
<thead>
<tr><th>Year</th>
    <th>Host Country</th>
    <th>Winner</th>
    <th>Loser</th>
    <th>Score (Win - Lose)</th>
</tr>
</thead>
<tbody id="matchData"></tbody>
</table>

The function that creates the table content utilizes W3C DOM table-modification methods:

// Draw table from 'jsData' array of objects
function drawTable(tbody) {
    var tr, td;
    tbody = document.getElementById(tbody);
    // loop through data source
    for (var i = 0; i < jsData.length; i++) {
        tr = tbody.insertRow(tbody.rows.length);
        td = tr.insertCell(tr.cells.length);
        td.setAttribute("align", "center");
        td.innerHTML = jsData[i].year;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].location;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].winner;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].loser;
        td = tr.insertCell(tr.cells.length);
        td.setAttribute("align", "center");
        td.innerHTML = jsData[i].winScore + " - " + jsData[i].losScore;
    }
}

The drawTable( ) function can be invoked via the onload event handler of the page, or, if you prefer, by a script embedded in the body anywhere below the skeleton table elements:

drawTable("matchData");

14.7.3 Discussion

The W3C DOM provides the key methods for making a table on the fly. The first is the insertRow( ) method of the table element object; the second is the insertCell( ) method of the table row element object. It's not enough just to insert a row or cell, however. You must also populate the inserted object with content.

When you invoke the insertRow( ) method, the code returns a reference to the newly generated row object. That reference becomes the object you use to invoke insertCell( ) for each cell in the row. The parameter for both methods is an integer indicating the position of the new row within the table or cell within the row. The example uses a simple programmatic technique of applying the length property of the collection of associated elements, which always points to the next one at the end of the series.

The choice to populate the content of the table cells via the innerHTML property is arbitrary. With a couple of more lines per cell, a fully W3C DOM-compliant approach could have been used instead. Assuming one more local variable, txt, defined at the top of the function, the replacement for each innerHTML assignment looks as follows:

txt = document.createTextNode(oneRecord.getElementsByTagName("year")[0].
   firstChild.nodeValue);
td.appendChild(txt);

Naturally, you are not limited to creating tables out of JavaScript data. JavaScript data objects can consist of the equivalent of lookup tables that interact with user input in forms. See Recipe 14.5 for an example of a select element being used as part of a user interface for embedded data lookup. Offloading these simple kinds of lookup tasks to the client frees the server for more important chores.

Note that IE 5 for the Macintosh does not support table modification methods. Other document tree modification techniques that involve tables and table components almost always crash the browser.

14.7.4 See Also

Recipe 14.5 for embedding JavaScript data into a page; Recipe 14.16 for sorting tables.

    [ Team LiB ] Previous Section Next Section