Tuesday, November 04, 2008

JavaScript to dynamically create an HTML table (grid)

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>


2 comments:

عامر ملک said...

Dear Bryans,

I am trying to get values from user to draw table grid using your code. But its not working.

Code link: http://justpaste.it/jm21


Thank you

Bryan Rudden said...

Try this:

https://gist.github.com/fragment2501/4713822719c3dc26a0e5

Hope that helps!