0

I need to Create a table from a loop that uses the data from an array.

I am using a sample code but i am having trouble trying to figure out how to get the loop to use an array to fill the data. I dont know what i need to put for the function portion or if I dont even need to worry about that?

<!Doctype html>
<html>
<head>
<script type="text/javascript">
function table()
{
    this.calcmul = calc;
}
 function calc(arg1,arg2)
 {
        var cars = ["Saab", "Volvo", "BMW"];
        var cars2 = ["Saab", "Volvo", "BMW"];
        return multi;   
 }
 var table2 = new table();  
</script>
</head>
<body>
<table border="solid 2px;" style="font-size:50px;">
    <thead><tr>
            <script>
            for(var j=1; j<=5; j++)
            {
                document.write("<th><label style= color:red;'>"+i+"</label></th>");
            }
            </script>
            </tr>
    </thead>
    <tbody>
        <script type="text/javascript"> 
for(var i =1; i<=5; i++)
{
    document.write("<tr>");
    for(var k=1; k<=2; k++)
        {
            var cars = i;
            var cars2 = k; 
            document.write("<td>"+table2.cars+"</td>"); 
        }
    document.write("</tr>"); 
}   
</script>
    </tbody>
</table>
</body>
</html>

I am trying to get the loop to create the table and list the data from the array

1 Answers1

0

First of all, you should check your code for errors!, for example, you have your </tbody> tag outside of the <script> tag.

As to display the data from one of the arrays you have there, I would do it something like this:

    <html>
    <head>
        <title></title>
    </head>
    <body>

        <table border="solid 2px;" style="font-size:50px;" id="myTable">

        </table>

    <script type="text/javascript">
            var cars = ["Saab", "Volvo", "BMW"];
            var table = document.getElementById("myTable");
            var tableHead = "<thead><th>Cars</th></thead>";
            table.innerHTML += tableHead; 
    //What the above line will do is add to "myTable" the element <thead> and the <th>, in this case it's just one.
            for(var i = 0; i<cars.length; i++)
            {   
    /*This loop will enter as long as index i isn't greater than all the elements of the cars array. 
In this case, as long as i doesn't exceed or equals 2, it will print things*/
                table.innerHTML += "<tbody><td>"+cars[i]+"</td></tbody>";
    /*Now, we add the element <tbody> with the respective tds,
 depending on the index it will print different things,
for example: in the first run, i = 0, so it will print the body as: <tbody><td>Saab</td></tbody>, why? well, because is the first element of the cars array, then it will continue to print the other values.*/
            }

    </script>
    </body>
    </html>

You can see the output in here: https://jsfiddle.net/40wszykn/

tomgo
  • 16
  • 4