1
function boardSize() {
  var rows = 3;

  var cols = 3;
  document.write("   <table>   ");
  for (i = 0; i < rows; i++) {
    document.write("<tr>");

    for (j = 0; j < cols; j++) {
      var btncolo;
      var btnarr = ["red", "blue", "yellow"];
      var x = Math.floor((Math.random() * 3) + 1);
      btncolo = btnarr[x - 1];

      var stringArray = ["<td><input type='button' style=backgroundcolor:'", btncolo, "' onclick='hitheadr('id')'>  </td>"];
      document.write(stringArray.join(""));
    }
    document.write("</tr>");
  }
  document.write("    </table>");
}

I have been trying with this for displaying table in the same page but I could not get the result.

I know the reason that I am using document.write() gives the result in other page.

What can I use to get the desired result?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • You can use this as a reference: http://stackoverflow.com/questions/14004117/create-div-and-append-div-dynamically – Rajesh Jan 31 '17 at 12:31

1 Answers1

0

You could create DOM elements and append it to the body, instead of writing it to the document, possibly after loading the page, which leads to strange results.

Some helpful methods:

function hitheadr(id) {
    return function () {
        console.log(id);
    };
}

function createTable(rows, cols, element) {
    function getButtonId(i, j) {
        return 'button' + i + '|' + j
    }

    var table = document.createElement('table'),
        tr, td, button, i, j,
        colors = ["red", "blue", "yellow"];

    for (i = 0; i < rows; i++) {
        tr = document.createElement('tr');
        for (j = 0; j < cols; j++) {
            td = document.createElement('td');
            button = document.createElement('button');
            button.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
            button.appendChild(document.createTextNode(getButtonId(i, j)));
            button.onclick = hitheadr(getButtonId(i, j));
            button.id = getButtonId(i, j);
            td.appendChild(button);
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    element.appendChild(table);
}

createTable(3, 3, document.body);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392