Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Html table using for loop

Please help with below mentioned scenario->

I am having wanna display values from 1 to 30 in a table such a way that nos 1,2,3 should come in one tag and like wise 4,5,6 in other tr tag ans so on till 30 value. I wanna use table for displaying values in a element of a table. wherein each value like "1" should display in one , no "2" should display in different <TD> and so on.

I mean to say that value "1" should be displayed in single <TD> of <Table> tag ,value "2" should be displayed in another <td> tag and so on ,Also after three subsequent <TD>s one <Tr> should be used. Output should be as folllows ->

1 2 3 
4 5 6
7 8 9

and so on!

Early response would be much appreciated. Thanks.

I have tried Code as given below,

<script type="text/javascript">

    document.write("        <table width='673' align='center' cellpadding='2' cellspacing='1'>");
    document.write("            <tr>");
    document.write("    <td valign = 'top'>");
    document.write("                </td>");

    document.write("            </tr>");

    var cnt = 0;
    for (var idx = 1; idx <= 30; idx++) 
    {
        cnt = cnt + 1;
        document.write("            <tr>");
            document.write("    <td valign = 'top'>");
            document.write("        <table width='100px' align='center' cellpadding='2' cellspacing='1'>");
            document.write("            <tr>");
            document.write("                <td align='center'>");
            document.write("                   " + idx + "");
            document.write("                </td>");
            document.write("            </tr>");
            document.write("            <tr>");
            document.write("                <td class='label'>");
            document.write("                    <span> name part : " + idx + "</span>");
            document.write("                </td>");
            document.write("            </tr>");
            document.write("            </table>");
            document.write("                </td>");
            if (cnt = 3) 
            {
                document.write("            </tr>");
            }
            if (cnt = 3) {
                cnt = 0;
            }

        }

    document.write("            </table>");
</script>
like image 571
hero123 Avatar asked Dec 21 '22 00:12

hero123


1 Answers

You can try something like this:

var mytable = "<table cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>";

for (var i = 1; i < 31; i++) {
  if (i % 3 == 1 && i != 1) {
    mytable += "</tr><tr>";
  }
  mytable += "<td>[" + i + "]</td>";
}

mytable += "</tr></tbody></table>";

document.write(mytable);

Here is a jsFiddle demo

like image 136
ajax333221 Avatar answered Jan 08 '23 19:01

ajax333221