Search code examples
javascripthtml-tablemultiplication

The multiplication table in javascript should show a table starting from 10 to 19


I am trying to print a multiplication table starting from 10 and up to 19. My temporary result is that it basically the same line that is repeating it self..

I tried to use the table, but it seems that it doesn´t work as desired.. I don´t know how to list all the numbers first from 10 til 19 in a row and in a column and then the product of the rows and columns in the other cells.

 <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body onLoad="gangetabellen()">

      <div id="tabell"></div>

      <script>

      function gangetabellen() {

        var tall1, tall2, produkt; 

        var tabell = "<table style='width:500px'>";

        for (tall1 = 10; tall1 <= 19; tall1++) {
          row += "<tr>";

          for (tall2 = 1; tall2 <= 19; tall2++) {

             produkt = tall1 * tall2;
             tabell += "<td>" + produkt + "</td>";
          }
          tabell += "</tr>";
        }

        tabell += "</table>";
        document.getElementById("tabell").innerHTML = tabell;

      </script>


      </body>
    </html>

it supposed to show

10  11 12 13 14 15 16 17 18 19
10 100 110
11 
12
13
14
15
16
17
18
19

Solution

  • You need to change two things:

    1. Add a } to close the function
    2. Change row += "<tr>"; (undeclared variable) to table += "<tr>";

    gangetabellen()
    <div id="tabell"></div>
    
    <script>
    
      function gangetabellen() {
    
        var tall1, tall2, produkt; 
    
        var tabell = "<table style='width:500px'>";
    
        // If you want a header you should add a for-loop here to add
        // a row with tall2
    
        for (tall1 = 10; tall1 <= 19; tall1++) {
          tabell += "<tr>";
    
          // If you want a header to the left you should add it here.
    
          for (tall2 = 1; tall2 <= 19; tall2++) {
    
             produkt = tall1 * tall2;
             tabell += "<td>" + produkt + "</td>";
          }
          tabell += "</tr>";
        }
    
        tabell += "</table>";
        document.getElementById("tabell").innerHTML = tabell;
      }
    
    </script>

    If you want to display tall1 and tall2 at the edges you need to add code for that (and you can use <th> instead of <td> for "table header". It makes it easier to style the table.