Create tr,td elements for a Table using JavaScript
In some situations we have to create table rows and columns dynamically.
In those cases javascript will give the better solution to create HTML elements dynamically.
we can dynamically create tr and td elements for table through javascript using document.createElement method.
Below you can find sample code to create tr and td elements for a table dynamically.
<html>
<head>
<title>Dynamically Created Table using javascript</title>
<script type="text/javascript">
function AddChild()
{
var objtable=document.getElementById('reportbody');
var r,c;
r=document.getElementById('txt1').value;
c=document.getElementById('txt2').value;
var i;
var j;
for(i=0;i<r;i++)
{
var elTR=document.createElement("tr");
for(j=0;j<c;j++)
{
var elTD1=document.createElement("td");
elTD1.style.color='red';
elTD1.style.border='1px solid #000';
elTD1.innerHTML="Test Message";
elTR.appendChild(elTD1);
}
elTR.style.border='3px solid black';
objtable.appendChild(elTR);
}
}
</script>
</head>
<body>
<div>
<table id="myreport" style="border:solid 1px #000000; ">
<tbody id="reportbody">
</tbody>
</table>
<br />
How many Rows you want to Add
<input type="text" id="txt1" name="txt1" /><br />
How many Coulmns you want to Add
<input type="text" id="txt2" name="txt2" /><br />
<input type="submit" id="btn_1" value="Add" onclick="AddChild();"/>
</div>
</body>
</html>
For the above code you need to supply how many rows and how many columns you want.
I this way you can create any HTML element dynamically through javascript by supplying it's name.
Download source code here
Subscribe
Filter by APML