-->

Pages

Friday 7 April 2017

How to create Tables dynamically using JavaScript !

We all use HTML tables on our web pages as they provide a sophisticated and better look to our website, however rather than writing the <tr> and <td> tag manually for the number of rows and columns in our table, we can simply create tables dynamically by using Javascript.


In this article of mine, I am going to provide a very simple javascript trick, a very simple code snippet to create tables dynamically.The code snippet is consisting of both a static table and a dynamic table generated using Javascript so that you guys can easily understand how easy it is to generate table dynamically by simple and less written code.

Here is the code snippet:

<!DOCTYPE html>
<html>
    <head>

        <title>Dynamic Table using JS</title>
       
    </head>
    <body>
        <h1>Static Table</h1>
        <table border="2">
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
            </tr>
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
            </tr>
             
        </table>
        <br/>
        <h1>Dynamic Table</h1>
        
        <script type="text/javascript">
           
           /*initializing variables*/
           
            var table=' ';
            var rows=5;
            var cols=5;

           //one for loop is for creating the rows

            for(var r=1;r<=rows;r++)
            {
                table+='<tr>';

               //another for loop is for creating the columns

                for(var c=1;c<=cols;c++)
                {
                    table+='<td>'+c+'</td>';
                }
                table+='</tr>';
            }
           //javascript function to write on webpage
          
         document.write('<table border=2>'+table+'</table>');
        
      </script>
    </body>
</html>

Screenshot:

That's it in this article of mine, as you guys can see it is that much simple to generate a dynamic table using Javascript, it provides the flexibility to the user to change rows and columns dynamically rather than typing the whole code again and again.

No comments:

Post a Comment

Thanks for Your Time!