JavaScript - Dynamic Creation of HTML Table - Asked By jeccinta jeccinta on 17-Aug-06 06:05 AM

I am very new to JavaScript and I need to create a dynamic HTML table using the values entered by the user,(no:of rows and no:of columns) in a html page.

The easiest way - Asked By Robbe Morris on 17-Aug-06 06:42 AM

is to set the .innerHtml property of a DIV tag with the contents of your html.  You just concatenate strings or stuff the strings in an array and then call the .Join() method.

You can rip that part of the code out of this sample:

http://www.eggheadcafe.com/articles/20020922.asp

Introduction to Dynamic HTML - Asked By J S on 17-Aug-06 06:58 AM

Check the code and change it according to u needs:

http://www.dynamicdrive.com/forums/showthread.php?t=175

samples :
http://www.oreillynet.com/pub/a/javascript/2003/05/06/dannygoodman.html

http://msdn.microsoft.com/workshop/author/dhtml/dhtml.asp

This is one of the best HTML DOM References - Asked By Peter Bromberg on 17-Aug-06 07:16 AM

you can find. It has "just enough" info:

http://www.w3schools.com/htmldom/dom_reference.asp
Creating Table Dynamically using Javascript - Asked By Chandu . on 17-Aug-06 11:53 AM
Hi Jeccinta,

You can create the table dynamically using the methods exposed by the DOM model.
HTML Code along with the Javascript depicts the same.
Here we are using three Javascript methods to create the table dynamically.

1)CreateTable(rowCount, colCount, srcHolder)
  This method is the base method and will trigger the creation of the table (for e.g. on the click event of a button etc).
	Thie method expects three parameters 
			rowCount(No of Rows the table should have.), 
			colCount(No of cells each row of the table should have.)
			srcHolder(Another HTML element like a DIV which should hold the Table)
	First we clear the contents of the srcHolder by setting the innerHTML property to blank.
	Then we dynamically create the table element using the document.createElement(<TAG_NAME>) method which returns a reference to the element created (here it will be a table element.)
	Then we call the AppendRow method iterating rowCount times.

2)AppendRow(srcTable)
	This is the method where we create the table row on the fly and add it to the newly created table as specified above.
	This metod returns a reference to newly created table row.
	Then we call the AppendCell method iterating colCount times.

3)AppendCell(srcRow)
	This is the method where we create the table cell on the fly and add it to the newly created table row as specified above.
	This metod returns a reference to newly created table cell.

Thiw is how the table will be created.
Also, the Javascript variables DEFAULT_WIDTH and DEFAULT_HEIGHT are used to specify the default height and width of the table.
You can tweak the code above by passing the Height and Width of the table as parameters to the CreateTable method.

In case the code below is not clear, let me know, I shall furthe clarify the same.

[CODE]
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>Dynamic Table</title>
	<meta name="Author" content="Chandra Vedantham">
	<meta name="Description" content="Html Page">
	<script>
		var DEFAULT_WIDTH = 100;
		var DEFAULT_HEIGHT = 100;

		function CreateTable(rowCount, colCount, srcHolder)
		{
			if(IsValidNumber(rowCount) && IsValidNumber(colCount) && (srcHolder != null) && (srcHolder.canHaveChildren))
			{
				srcHolder.innerHTML = "";
				var srcTable = document.createElement("table");
				srcTable.border = 1;
				srcTable.borderColor = "Black";
				srcTable.height = DEFAULT_HEIGHT;
				srcTable.width = DEFAULT_WIDTH;
				var tmpRow = null;
				var tmpCell = null;
				srcHolder.appendChild(srcTable);
				for(i=0; i<rowCount; i++)
				{
					tmpRow = AppendRow(srcTable)
					for(j=0; j<colCount; j++)
					{
						tmpCell = AppendCell(tmpRow);
						tmpCell.innerText = j;
						tmpCell = null;
					}
					tmpRow = null;
				}
			}
		}

		function AppendRow(srcTable)
		{
			if(srcTable != null)
			{
				return srcTable.insertRow();
			}
			else
			{
				alert("Error while creating table. Cause: Container Table is null!");
			}
		}

		function AppendCell(srcRow)
		{
			if(srcRow != null)
			{
				return srcRow.insertCell();
			}
			else
			{
				alert("Error while creating table. Cause: Container row is null!");
			}
		}

		function IsValidNumber(ipNum)
		{
			if(isNaN(ipNum))
			{
				alert("Invalid Number!");
				return false;
			}
			else if(ipNum < 1)
			{
				alert("Number should be greater than 0!");
				return false;
			}
			else
			{
			return true;
			}
		}
	</script>
</head>
<body>
	<table>
	<tr>
		<td>No. Of Rows: </td>
		<td><input type=text name=txtRows value=1 /></td>
	</tr>
	<tr>
		<td>No. Of Columns: </td>
		<td><input type=text name=txtCols value=1 /> </td>
	</tr>
	<tr>
		<td colspan=2 align=right><input type=button name=cmdCreate value="Create Table" onClick="CreateTable(txtRows.value, txtCols.value, divHolder)" /></td>
	</tr>
	</table>
	<div id=divHolder>
		
	</div>
</body>
</html>
[/CODE]
How to write my own text into the cells - Asked By jeccinta jeccinta on 18-Aug-06 12:59 AM
Hi,
  The code u have sent is very useful.BUt in that we get the numbers as 0,1,2,inside the cells.But in my application user will write his own values inside the cells...How to do this??

Very very urgent..Thanx in advance...
user text in dynamic table cells - Asked By mv ark on 18-Aug-06 04:46 AM
Here is the code to add a text boxes to the dynamic table cells, where the user can enter his own values, 


<script>
    function start() {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates a <table> element and a <tbody> element
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < 2; j++) {
            // creates a <tr> element
            mycurrent_row = document.createElement("tr");
            for(var i = 0; i < 2; i++) {
                // creates a <td> element
                mycurrent_cell = document.createElement("td");
                // creates a text node
	  mycurrent_txtbox = document.createElement("input");
	  mycurrent_txtbox.setAttribute('type',"text");
                //currenttext = document.createTextNode("cell is row "+j+", column "+i);
                // appends the text node we created into the cell <td>
                //mycurrent_cell.appendChild(currenttext);
	mycurrent_cell.appendChild(mycurrent_txtbox);
                // appends the cell <td> into the row <tr>
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row <tr> into <tbody>
            mytablebody.appendChild(mycurrent_row);
        }
        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border", "2");
    }
</script>
</head>
<body onload="start()">
</body>


Also check these links -
http://developer.mozilla.org/en/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
Somya replied to jeccinta jeccinta on 07-Jul-11 07:03 AM
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
var y=1,k=1,l=1,val=0,cnt=0,r=0,m=0;
var arr=new Array();
function addRow(tableID)
{
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
		
	 val=val+1;
	  var row = table.insertRow(rowCount);
	  var colCount = table.rows[0].cells.length;
	  //alert(colCount);
	 for(var i=0; i<colCount; i++) 
	  {
			  
		      var newcell= row.insertCell(i);
		       if(i==colCount-1)
		      {
		    	 if(!addRow.counter)
		    	  {
					addRow.counter = 0;
		    	  }
		    	  addRow.counter++;	
		    	  newcell.innerHTML = "<input align=middle type=button width='100' name='btnRmv_"+addRow.counter+"' id='btnRmv_"+addRow.counter+"' value='Remove' onclick='removeRow(this,"+tableID+","+colCount+","+k+");' onChange='removeRow(this,"+tableID+","+val+","+k+");' />";
				  k++;
			  }
		      else 
		      {
       	  	if(i==0  )
       	  	{
       	      if(!addRow.counter)
       	      {
       	  		addRow.counter = 0;
       	  	  }
       	  	  addRow.counter++;	
       	  	  newcell.innerHTML = "<label id='srno_"+addRow.counter+"' style='position:relative' width ='50' > "+rowCount+" </label>"; 
       	  	  rowCount=rowCount+1;;
       	  	}
       	  	if(i==1)
       	  	{
       	  		if(!addRow.counter)
       	  			addRow.counter = 0;
       	  		addRow.counter++;			//1
       	  		newcell.innerHTML = "<input name='txtGr_"+addRow.counter+"'id='txtGr_"+addRow.counter+"' type='text'  size='10' maxlength='15' align='middle' />";
       	  	}
       	  	if(i==3)
       	  	{
       	  		if(!addRow.counter)
       	  			addRow.counter = 0;
       	    	addRow.counter++;				//2
       	  		newcell.innerHTML ="<select txtGr_"+addRow.counter+"'id='txtGr_"+addRow.counter+"' onchange=''type='select-one'>" +
       	  					"<option value=''>Select--</option>" +
       	  					"<option value='ssc'>SSC</option>" +
       	  					"<option value='hsc'>HSC</option>" +
       	  					"<option value='graduate'>Graduate</option>" +
       	  					"<option value='pg'>Post Graduate</option>" +
       	  					"<option value='others'>Others...</option></select>";
       	  			
       	  	}	
       		if(i==2){
   	        	
       	  		if(!addRow.counter)
       	  			addRow.counter = 0;
       	  			addRow.counter++;				//3
       	  		newcell.innerHTML = "<input align=middle name='txtGr_"+addRow.counter+"' id='txtGr_"+addRow.counter+"' type='text'  size='10' maxlength='15' />";
       	  			
       	  	}	
       		
     switch(newcell.childNodes[0].type) {
     	      case "text": 
       	      
       	  		var j=i+1;
       	  		newcell.childNodes[0].value = "";
       	  		var cnt=rowCount+1;
       	  		
       		
             		var str=newcell.childNodes[0].name;
             		var len=str.length;
             		
             		var strname=str.substring(0,len);
             		newcell.childNodes[0].name=strname;
             		break;
       
       
         case "select-one":
             		newcell.childNodes[0].selectedIndex = 0;
             		cnt=rowCount+1;
             		str=newcell.childNodes[0].name;
             		len=str.length;
             		strname=str.substring(0,len);
             		newcell.childNodes[0].name=strname;
             break;
     			}
             }
}
}//      End Add Row Function


	
function removeRow(src,tableID,rowC,u)
{
		val--;
		u=u-1;
		var flag=0;
		var oRow = src.parentElement.parentElement;
		var row = tableID.deleteRow(oRow.rowIndex);
		if (cnt>=1)
		{
			arr[m++]=(u*rowC)+1;
			for( var j=0;j<(val+arr.length);j++)
			{ 
				for(var t=0;t<arr.length;t++)
				{
					if(arr[t]==y)
					{
						y=y+rowC;
						flag=1;
					}
				}
				if(flag==0)
				{
					if(document.getElementById("srno_"+y)==null)
					{
						
						y=y+rowC;
					}
					else
					{
					document.getElementById("srno_"+y).innerText=l++;
					y=y+rowC;
					}
				}
				else
				{
				 flag=0;
				}
		    }
		}
		if(cnt==0)
		{
			for( var j=0;j<(val);j++)
			{
				if(j==u)
				{
					arr[m++]=y;
					y=y+rowC;
				}
				document.getElementById("srno_"+y).innerText=l++;
				y=y+rowC;
			}
		}
		
		l=1;
		y=1;
		cnt++;
		return true;

}







</script>

</head>
<body>
<form name="form1" method="post" action="">
    
	<table id="dynamic_gen" border="1" align="center" >
	<tr >
	<th width="50" > Sr. No.</th>
   <th width="73"> Name </th>
   <th width="73">  SurName  </th>
      <th width="93">  Qualification </th>
   <th width="100"><input type="button" value="Add User" onclick="addRow('dynamic_gen')" /></th>
   </tr>
   
   
</table>    

</form>



</body>
</html>
<html>
<head>
 
<title>Insert title here</title>
<script>
var y=1,k=1,l=1,val=0,cnt=0,r=0,m=0;
var arr=new Array();
function addRow(tableID)
{
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
     
   val=val+1;
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
    //alert(colCount);
   for(var i=0; i<colCount; i++)
    {
         
        var newcell= row.insertCell(i);
         if(i==colCount-1)
        {
         if(!addRow.counter)
          {
          addRow.counter = 0;
          }
          addRow.counter++;
          newcell.innerHTML = "<input align=middle type=button width='100' name='btnRmv_"+addRow.counter+"' id='btnRmv_"+addRow.counter+"' value='Remove' onclick='removeRow(this,"+tableID+","+colCount+","+k+");' onChange='removeRow(this,"+tableID+","+val+","+k+");' />";
          k++;
        }
        else
        {
      if(i==0  )
      {
        if(!addRow.counter)
        {
        addRow.counter = 0;
        }
        addRow.counter++;
        newcell.innerHTML = "<label id='srno_"+addRow.counter+"' style='position:relative' width ='50' > "+rowCount+" </label>";
        rowCount=rowCount+1;;
      }
      if(i==1)
      {
        if(!addRow.counter)
          addRow.counter = 0;
        addRow.counter++;       //1
        newcell.innerHTML = "<input name='txtGr_"+addRow.counter+"'id='txtGr_"+addRow.counter+"' type='text'  size='10' maxlength='15' align='middle' />";
      }
      if(i==3)
      {
        if(!addRow.counter)
          addRow.counter = 0;
        addRow.counter++;         //2
        newcell.innerHTML ="<select txtGr_"+addRow.counter+"'id='txtGr_"+addRow.counter+"' onchange=''type='select-one'>" +
              "<option value=''>Select--</option>" +
              "<option value='ssc'>SSC</option>" +
              "<option value='hsc'>HSC</option>" +
              "<option value='graduate'>Graduate</option>" +
              "<option value='pg'>Post Graduate</option>" +
              "<option value='others'>Others...</option></select>";
           
      }  
      if(i==2){
         
        if(!addRow.counter)
          addRow.counter = 0;
          addRow.counter++;         //3
        newcell.innerHTML = "<input align=middle name='txtGr_"+addRow.counter+"' id='txtGr_"+addRow.counter+"' type='text'  size='10' maxlength='15' />";
           
      }  
       
   switch(newcell.childNodes[0].type) {
        case "text":
         
        var j=i+1;
        newcell.childNodes[0].value = "";
        var cnt=rowCount+1;
         
       
          var str=newcell.childNodes[0].name;
          var len=str.length;
           
          var strname=str.substring(0,len);
          newcell.childNodes[0].name=strname;
          break;
      
      
     case "select-one":
          newcell.childNodes[0].selectedIndex = 0;
          cnt=rowCount+1;
          str=newcell.childNodes[0].name;
          len=str.length;
          strname=str.substring(0,len);
          newcell.childNodes[0].name=strname;
       break;
        }
       }
}
}//    End Add Row Function
 
 
   
function removeRow(src,tableID,rowC,u)
{
    val--;
    u=u-1;
    var flag=0;
    var oRow = src.parentElement.parentElement;
    var row = tableID.deleteRow(oRow.rowIndex);
    if (cnt>=1)
    {
      arr[m++]=(u*rowC)+1;
      for( var j=0;j<(val+arr.length);j++)
      {
        for(var t=0;t<arr.length;t++)
        {
          if(arr[t]==y)
          {
            y=y+rowC;
            flag=1;
          }
        }
        if(flag==0)
        {
          if(document.getElementById("srno_"+y)==null)
          {
             
            y=y+rowC;
          }
          else
          {
          document.getElementById("srno_"+y).innerText=l++;
          y=y+rowC;
          }
        }
        else
        {
         flag=0;
        }
      }
    }
    if(cnt==0)
    {
      for( var j=0;j<(val);j++)
      {
        if(j==u)
        {
          arr[m++]=y;
          y=y+rowC;
        }
        document.getElementById("srno_"+y).innerText=l++;
        y=y+rowC;
      }
    }
     
    l=1;
    y=1;
    cnt++;
    return true;
 
}
 
 
 
 
 
 
 
</script>
 
</head>
<body>
<form name="form1" method="post" action="">
   
  <table id="dynamic_gen" border="1" align="center" >
  <tr >
  <th width="50" > Sr. No.</th>
   <th width="73"> Name </th>
   <th width="73">  SurName  </th>
    <th width="93">  Qualification </th>
   <th width="100"><input type="button" value="Add User" onclick="addRow('dynamic_gen')" /></th>
   </tr>
    
    
</table>   
 
</form>
 
 
 
</body>
</html>