0

I am trying to use javascript to create an HTML table after the user is prompted to enter how many rows and columns they would like. This table is to be filled with randomly generated colors, but I cannot figure out why the table is not being generated to begin with.

<script type="text/javascript">
var colors = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
function createTable()
{
    var num_rows = prompt("How many rows?");
    var num_cols = prompt("How many columns?");
    var theader = '<table border="1">\n';
    var tbody = '';

    for( var i=0; i<num_rows;i++)
    {
        tbody += '<tr>';
        for( var j=0; j<num_cols;j++)
        {
            tbody += '<td>';
            tbody += colors;
            tbody += '</td>';
        }
        tbody += '</tr>\n';
    }
    var tfooter = '</table>';
    document.getElementById('shell').innerHTML = theader + tbody + tfooter;
}
var choice = prompt("create table?");
if (choice !== 0) {
    createTable();
}

</script>
<body id='shell'>

</body>
AwBi
  • 1

1 Answers1

0

The problem is that the javascript is running before the body of the page has been created. If you look in the console you should see an error:

test.html:23 Uncaught TypeError: Cannot set property 'innerHTML' of null
at createTable (test.html:23)
at test.html:27
createTable @ test.html:23
(anonymous) @ test.html:27

One common solution would be to leave the code in the header, but only call it on load (as described here How do I call a JavaScript function on page load?)

that code would look something like this:

window.onload = function() {
  var choice = prompt("create table?");
    if (choice !== 0) {
        createTable();
    }
};

Note that you are putting text in the cells, not actual colors (which would involve setting styles).

tomf
  • 439
  • 4
  • 13