Search code examples
javascripthtmlmatrixhtml-tablenested-loops

How to create a user generated matrix in javascript/html while having the table label each cell incrementally


Well hello hello everyone, new to javascript. I received an assignment and am at a bit of a standstill. I need to have a user-generated table that labels itself. I am having a hard enough time getting the table to generate properly with the input from prompts. Now I am also stuck with the loop needed for the labeled rows and columns as well. It May seem ridiculous how simple this is but I am exhausted and receiving little guidance and could use the help.

The table should look like this. I can't even get the table to generate properly with loops yet.
[1][2][3][4]
[5][6][7][8]

<!DOCTYPE html>
<script>
 var row = prompt("how many rows would you like?");
 var col = prompt("how many colums would you like?");
</script>
<body>
  <script>
    var mytable = "";
    var cellNum = 0;
    for (var r = 0; r < row ; r++);
    {
      mytable += "<tr>";
       for (var c = 0 ; c < col; c++ );
      {
        mytable += "<td>" + cellNum++; + "</td>";
      }
    mytable += "</tr>";

    }

  document.write("<table border=1>" + mytable + "</table>");
  </script>
</body>

Solution

  • You basically put a semicolon behind the first for loop.

    for (var c = 0 ; c < col; c++ );
    

    Right version would be this piece of code:

    for (var c = 0 ; c < col; c++ )
    

    I also would change

    for (var r = 0; r < row ; r++)
    

    into

    for (var r = 0; r < row-1 ; r++)
    

    or you gonna end up with a empty row.

    Have a great day!