JavaScript to dynamically create an HTML table (grid)

less than 1 minute read

Sample code for Genzir to use in creating an HTML table for a map grid based on sequential x/y coordinates.


<html>

    <head>

        <title>A tabular grid generated with javascript via x/y for loops</title>

    </head>

    <body>

        <p>

        This demonstrates a very simple for-loop approach to generating a tabular grid.

        You can specifiy the range of x and y coordinate values in the javascrpt code.

        </p>

        <table border="1">

            <script language="JavaScript">

                // define x/y coordinate ranges

                var x_start = 1;

                var x_end = 10;

                var y_start = 1;

                var y_end = 10;

                // loop over all x values (rows) sequentally

                for( var x=x_start; x <= x_end; x++ ){

                    // open the current row

                    document.write('<tr>');

                    // loop over all y values (cols) sequentally

                    for( var y=y_start; y <= y_end; y++ ){

                        // write out the current x/y coordinate with a table cell

                        document.write('<td>image x:'+x+' y:'+y+'</td>');

                    }

                    // end the current row

                    document.write('</tr>');

                }

            </script>

        </table>

    </body>

</html>