Transforming JavaScript Data into HTML Tables
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Example File From "JavaScript and DHTML Cookbook"
Published by O'Reilly & Associates
Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 14.7</title>
<link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" />
<style type="text/css">
table {table-collapse:collapse; border-spacing:0}
td {border:2px groove black; padding:7px; background-color:#ccffcc}
th {border:2px groove black; padding:7px; background-color:#ffffcc}
.ctr {text-align:center}
</style>
<script type="text/javascript">
// 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};
// 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;
}
}
</script>
</head>
<body onload="drawTable('matchData')">
<h1>Transforming JavaScript Data into HTML Tables</h1>
<hr />
<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>
</body>
</html>
Related examples in the same category