Firebug shows you the HTML as it understands it. So if it doesn't look
right, it usually means you are creating invalid HTML.

The biggest problem with your example, is that you are calling
append() repeatedly, and I don't think the elements are being inserted
where you expect. What type of element is #mytable? If it is an anchor
tag, then you are appending your entire table inside an "a" element!
Probably not what you wanted.

I would suggest you use strings to build your HTML, and then just add
it all at once. Cleaner, simpler and faster. Something like...

var r = '';
for (...) {
  r += "<tr><td>" + data + "</td>.....</tr>";
}

$('#a-div-to-hold-your-table').html('<table>'+r+'</table>');

-jason

On Jan 19, 1:59 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> 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

Reply via email to