0

How can I dynamically generate an HTML <table> with a variable number of rows?

The number of rows will depend on the number of properties that exist within a Javascript object.

function showTable(trnum) //number of table rows passed in
{
   // how?
   // $("#elem").foo // #elem - element container for table
}
0

3 Answers 3

2
function showTable(trnum) {
    var tableCode = "<table>";
    for (var i=0; i<trnum; i++) {
        tableCode += "<tr>" + "stuff inside each tr ?" + "</tr>";
    }
    tableCode += "</table>";
    $("#elem").append(tableCode);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You missed to add the TD tags within rows and its seems the code is also creating an extra ending TR tag. Isn't it?
Extra ending TR tag should be table tag.
Indeed, the last tag is a </table> ! And he did not specify how he wanted the <td> tags to be inserted, that's why I wrote "stuff inside each tr ?" instead.
0

Follow the link. Generating HTML Tables with jQuery. For demo go here

2 Comments

You left the line numbers in the code in your jsFiddle, and you forgot to set the framework to jQuery. Also you didn't call the js function to create the table. I've updated your jsFiddle, you can change your link to http://jsfiddle.net/dJUKd/3/
@Sylvain. Thanks for doing so.... :-)) FYI the specified things were already there and demo was working fine.
0

You could give this a try:

$.createTable = function(trnum)
{
    var reps = new Array(trnum);
    var table = $('<table></table>');
    $.each(reps,function(){ 
        var td    = $('<tr><td> Stuff here </td></tr>');
        table.append(td)     
    }); 
    $('#elem').append(table);
}

Calling function:

$.createTable(6);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.