0

If I just link the script to start once the html page is loaded, it runs the javascript how I want it to and outputs the result in the same page, however if I link the script to a button, it outputs the code to a separate html page that has only the output on it.

<body>
<p>Creates a simple multiplication table asking the user to input the number of rows and columns that they want.</p>
<button onclick="myFunction()" class="button_1" >Start Table</button>
<div id="resultDiv"></div>
<script type="text/javascript">
function myFunction(){
    var rows = prompt("How many rows for your multiplication table?");
    var cols = prompt("How many columns for your multiplication table?");

    if(rows == "" || rows == null)
         rows = 10;
    if(cols== "" || cols== null)
         cols = 10;
    createTable(rows, cols);

    function createTable(rows, cols)
    {
      var j=1;
      var output = "
    <table border='1' width='465' cellspacing='0'cellpadding='5'>";
      for(i=1;i<=rows;i++)
      {
        output = output + "
        <tr>";
        while(j<=cols)
        {
          output = output + "
            <td>" + i*j + "</td>";
          j = j+1;
        }
         output = output + "
        </tr>";
         j = 1;
    }
    output = output + "
    </table>";
    onclick = document.write(output);
    }
document.getElementById("resultDiv").innerHTML = total; 
}   

</script>
</body>

I want the output of the table to show below where the button is, but only after the button is pressed and the two variables have been inputted using a prompt. While all I'm getting when using the button is the redirect to a separate html page.

1 Answers1

0

const resultDiv = document.getElementById('resultDiv');

function myFunction() {
  let rows = prompt('How many rows for your multiplication table?');
  let cols = prompt('How many columns for your multiplication table?');

  if (rows == '' || rows == null) rows = 10;
  if (cols == '' || cols == null) cols = 10;

  resultDiv.innerHTML = createTable(rows, cols);
}

function createTable(rows, cols) {
  let j = 1;
  let output = ` <table
    border = "1"
    width = "465"
    cellspacing = "0"
    cellpadding = "5" > `;
  for (let i = 1; i <= rows; i++) {
    output += `<tr>`;
    while (j <= cols) {
      output += `<td>${i * j}</td>`;
      j = j + 1;
    }
    output += `</tr>`;
    j = 1;
  }
  output += `</table>`;

  return output;
}
<html>

  <body>
    <p>
      Creates a simple multiplication table asking the user to input the number of rows and columns that they want.
    </p>
    <button onclick="myFunction()" class="button_1">Start Table</button>
    <div id="resultDiv"></div>
  </body>

</html>
WASD
  • 310
  • 1
  • 9