Generating random numbers is a common question found on many forum sites. Generating random numbers is useful in many types of applications. You can use it in games that use dice, display random images, generate random links, etc. We will take these two goals and develop a solution that will create a dynamically generated HTML table and populate the cells with random numbers.

Creating a Dynamic HTML Table

Using JavaScript to create a dynamic table element, or any other element for that matter is fairly easy and straightforward. This tutorial is not going to cover the details related to the Document Object Model (DOM) or how to traverse the DOM. For the purposes of this tutorial, the code example shown below can be used to create a dynamic table element by creating the element nodes and inserting them into the document tree. If you are new to HTML, it is a good idea to read up on the Document Object Model.

Generating Random Numbers

In JavaScript, we can use the Math.random() method to generate a random number. This method generates a random number between 0-1. Because of this, we need to multiple this value by the maximum number that we want to include in our range. In the example below, we took an additional step to incorporate a minimum and maximum range. In addition, we use Math.Floor() method to remove the values after the decimal point in the random value. Because we are using the Math.floor() method, we need to add 1 to the value to ensure that the answer is within the range because the Math.floor() method rounds a number down to the nearest integer (it simply removes values after the decimal point). Math.floor() + 1, unlike Math.round() will ensure that the result is not generating more numbers in the higher range of our number spectrum.

Examples for Generating Random Numbers

Example

The following HTML example contains the HTML, CSS, and JavaScript necessary to build a dynamic HTML table. There are four variables in the JavaScript block. You can modify the variable’s values to adjust the number of rows in the table, the number of cells within each row, and the minimum and maximum range of numbers that are used in random number generation. The random numbers generated will be placed within each cell of the table.