[jQuery] creating a table from an array
My use case is pretty common and surely it is in some tutorial but I
cannot find the right place
where to look, so let me post here. I would like to generate an HTML
table from JSON data
coming from a server.
I am a very green when it comes to Javascript, so naively I wrote the
following
code:
var a = [["a","b","c"],[1,2,3],[4,5,6]]; // the array will be read
from the server in the real app
$("#mytable").click(function()
{
$
(this).append("<table>");
$
(this).append("<thead>");
$
(this).append("<tr>");
for(j=0; j<3; j++)
{
$(this).append("<th>" + a[0][j] + "</
th>");};
$(this).append("</
tr>");
$(this).append("</
thead>");
$
(this).append("<tbody>");
for(i=1; i<3; i++)
{
$
(this).append("<tr>");
for(j=0; j<3; j++)
{
$(this).append("<td>" + a[i][j] + "</
td>"); };
$(this).append("</
tr>"); };
$(this).append("</
tbody>");
$(this).append("</
table>");
});
When I click on #mytable and I look at the generated HTML with Firebug
I get
<table/>
<thead/>
<tr/>
<th>a</th>
<th>b</th>
<th>c</th>
<tbody/>
<tr/>
<td>1</td>
<td>2</td>
<td>3</td>
<tr/>
<td>4</td>
<td>5</td>
<td>6</td>
What's happening here? It seems .append is inserting closed tags
instead of what I told
it to append. I am pretty convinced that I should have generated the
tags with
document.createElement instead, but I did expect .append to work for
a quick and
dirty experiment. Anybody here can shed some light?
TIA,
Michele Simionato