Friday, October 17, 2014

how to create dynamic table?



Sometimes ago, when i was developing a Web Application then i'd need to create dynamic table. I did google but nothing found useful for me. Then i decided to develop it by myself. Although it took some great time but yes, the outcome was fabulous.
Here is the code.
 Dyntable.js
function getVal()
{
var val=document.frm.txt1.value
var str="<table border='2'><tr> 
<th nowrap='nowrap'><font color='blue' size='2'>Item 1</font></th>
<th><font color='blue' size='2'>Item 2</font></th>
<th><font color='blue' size='2'>Item 3</font></th> 
</tr>" 
//validation logic for each table's cell 
var b=0;
while(val>0)
{
str=str+"<tr><td>
<input type='text' name='jtext"+ ++b 
+"' onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") 
} 
else if(this.value<=0) 
{ alert(\"Value must be greater than zero !!!\") 
} '/></td><td><input type='text' name='jtext"+ ++b 
+"' onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") } 
else if(this.value<=0) { 
alert(\"Value must be greater than zero !!!\") 
} '/></td><td>
<input type='text' name='jtext"+ ++b +"' 
onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") } 
else if(this.value<=0) { 
alert(\"Value must be greater than zero !!!\") } '/>
</td></tr>";
val--;
} 
str=str+"</table>"; 

document.getElementById("spn").innerHTML=str;
} 

Htmlcode.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dynamic table</title>
</head>
<script language="javascript" src="Dyntable.js"> </script>
<body>
<center>
<h1>Dynamic table</h1>
<form name="frm">
<input type="text" size="20" name="txt1">
</br></br>
<input type="button" value="ok" name="okbtn" onclick='getVal()'>
</form>
<p>
<span id="spn"></span>
</center>

</body>
</html>



Here is Output: