Generate Tables Dynamically in HTML using JavaScript

Download PDF Version

Hello Friends,

This is my first technical article. When I was new to HTML, I needed to generate table dynamically in HTML displaying data from database. The only way we can code HTML content dynamically at client end is to use client -end scripting language. So I used JavaScript to Generate Table. I stored all of my data in Arrays from database. Then using that data I generated table in HTML from JavaScript.

Here is an example code how to generate table dynamically in HTML using JavaScript.

DynTab.html


<html>
<head>
     <title>Dynamic Tables in HTML</title>
</head>
<body>
      
	<script language = "javascript">
		var arrdyn = new Array();
		var arr = new Array();
		
		arr[0] = prompt("Please Enter Your Name");
		arr[1] = prompt("Please Enter Your E-Mail");
		arr[2] = prompt("Enter Second Person Name");
		arr[3] = prompt("Enter Second Person E-Mail");
		arr[4] = prompt("Enter Third Person Name");
		arr[5] = prompt("Enter Third Person E-Mail");
		
		arrdyn[1] = new Array(arr[0],arr[1]);
		arrdyn[2] = new Array(arr[2],arr[3]);
		arrdyn[3] = new Array(arr[4],arr[5]);
		
		document.write('<table border="1">');

			document.write('<tr>');
				document.write('<th colspan="3">Welcome '+ arrdyn[1][0] + ' to Dynamic Table Generation </th>');
			document.write('</tr>');
			
			document.write('<tr>');
				document.write('<th>SNo.</th>');
				document.write('<th>Name</th>');
				document.write('<th>E-Mail ID</th>');
			document.write('</tr>');	
			
			for (var i=1; i<4;i++)
			{
				document.write('<tr>');
					document.write('<td>' + i + '</td>');
					document.write('<td>' + arrdyn[i][0] + '</td>');
					document.write('<td>' + arrdyn[i][1] + '</td>');
				document.write('</tr>');	
			}
			
			document.write('<tr>');
				document.write('<th colspan="3">Thank You Visitor</th>');
			document.write('</tr>');
			
		document.write('</table>');
	</script>
   
</body>
</html>

In this example:
When page loads, it will take input from user to fill the array. Using that array, it will generate and HTML table.

newsletter software