Dynamically Add/Remove rows in HTML table using JavaScript

A good web design involves the better user interaction and ability to fetch the data in a better way. For fetching user data, you may have to create a form wherein user can add multiple entries and submit them simultaneously.

Thus for this you will need a way to add or remove fields dynamically into the HTML page. In my previous article, I had discussed about the way one can add dynamic form components into the web page.

In this article we will create a user interface where user can add/delete multiple rows in a form using JavaScript.

First check the user interface.
dynamic-add-delete-row-table-javascript

In this example, we have created a table which will display our html components. On pressing Add Row, a dynamic row will be created and added in the table. And on selecting the checkbox and pressing Delete Row, the row will be removed.

Following is the source.

Code

<HTML>
<HEAD>
	<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
	<SCRIPT language="javascript">
		function addRow(tableID) {

			var table = document.getElementById(tableID);

			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);

			var cell1 = row.insertCell(0);
			var element1 = document.createElement("input");
			element1.type = "checkbox";
			element1.name="chkbox[]";
			cell1.appendChild(element1);

			var cell2 = row.insertCell(1);
			cell2.innerHTML = rowCount + 1;

			var cell3 = row.insertCell(2);
			var element2 = document.createElement("input");
			element2.type = "text";
			element2.name = "txtbox[]";
			cell3.appendChild(element2);


		}

		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;

			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					table.deleteRow(i);
					rowCount--;
					i--;
				}


			}
			}catch(e) {
				alert(e);
			}
		}

	</SCRIPT>
</HEAD>
<BODY>

	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

	<TABLE id="dataTable" width="350px" border="1">
		<TR>
			<TD><INPUT type="checkbox" name="chk"/></TD>
			<TD> 1 </TD>
			<TD> <INPUT type="text" /> </TD>
		</TR>
	</TABLE>

</BODY>
</HTML>

For adding dynamic row in table, we have used insertRow() method. This method will insert a row at position specified by the index arguement. Also for removing row, we have used deleteRow() method.
Note that for inserting dynamic row, we have to created cells by using row.insertCell() method.

Check the online demo.

Online Demo


Click here.

Add/Remove rows from table having Drop Down List

What if my table has a selectbox or drop down list and I want to implement add/remove row functionality? A lot of people asked me this question (you can check comment section), so I thought to update this article and add one more case. Adding / Removing rows in a table having drop down list.

Following is the code:

<HTML>
<HEAD>
	<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
	<SCRIPT language="javascript">
		function addRow(tableID) {

			var table = document.getElementById(tableID);

			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);

			var colCount = table.rows[0].cells.length;

			for(var i=0; i<colCount; i++) {

				var newcell	= row.insertCell(i);

				newcell.innerHTML = table.rows[0].cells[i].innerHTML;
				//alert(newcell.childNodes);
				switch(newcell.childNodes[0].type) {
					case "text":
							newcell.childNodes[0].value = "";
							break;
					case "checkbox":
							newcell.childNodes[0].checked = false;
							break;
					case "select-one":
							newcell.childNodes[0].selectedIndex = 0;
							break;
				}
			}
		}

		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;

			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					if(rowCount <= 1) {
						alert("Cannot delete all the rows.");
						break;
					}
					table.deleteRow(i);
					rowCount--;
					i--;
				}


			}
			}catch(e) {
				alert(e);
			}
		}

	</SCRIPT>
</HEAD>
<BODY>

	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

	<TABLE id="dataTable" width="350px" border="1">
		<TR>
			<TD><INPUT type="checkbox" name="chk"/></TD>
			<TD><INPUT type="text" name="txt"/></TD>
			<TD>
				<SELECT name="country">
					<OPTION value="in">India</OPTION>
					<OPTION value="de">Germany</OPTION>
					<OPTION value="fr">France</OPTION>
					<OPTION value="us">United States</OPTION>
					<OPTION value="ch">Switzerland</OPTION>
				</SELECT>
			</TD>
		</TR>
	</TABLE>

</BODY>
</HTML>

Check the addRow() method in above code. I have edited this piece of code from our previous example. The addRow() method iterates through all the columns and copy the content of 1st column to new column. This way a new row is created which is exact copy of 1st row. Also the switch{} case in the code make sure that the value are not copied as it is. For example, if you have entered text “abc” in textbox of 1st row and you press Add Row button, the new row will be added and the textbox of this new row will have value “abc”. So to make sure the values are not copied, we have added the switch{} code.

You may want to comment the switch{} code if the copying of the values in newly added row if desired to you.

Online Demo


Click here.

Getting Submitted Form Values in PHP

The main purpose of above code is to take input from user and persist it in database. Hence we may want to submit the above form and fetch its values in PHP to store the data in database.

If you notice we have multiple input textboxes with the same name. So in order to get these values in PHP request parameter, we need to modify our HTML. We need to append [] at the end of name of each input boxes including select box.

Thus our textbox definition:

<INPUT type="text" name="txt">

Will change into:

<INPUT type="text" name="txt[]">

Also the checkbox and select box definition change to:

<INPUT type="checkbox" name="chk[]"/>

<SELECT name="country[]">
	<OPTION value="in">India</OPTION>
	<OPTION value="de">Germany</OPTION>
	<OPTION value="fr">France</OPTION>
	<OPTION value="us">United States</OPTION>
	<OPTION value="ch">Switzerland</OPTION>
</SELECT>

Once we have changed the HTML code, add a submit button at the end of the form and submit this form to Fetchrequest.php

Following will be the code to get the values from request in PHP and displaying them on screen:

<?php
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
$country = $_POST['country'];

foreach($txtbox as $a => $b)
  echo "$chkbox[$a]  -  $txtbox[$a]  -  $country[$a] <br />";

?>

If you read this far, you should follow me on twitter here.



400 Comments

  • Coder 25 February, 2013, 17:30

    Thanks dear ……ur awesome

  • Zeb 27 February, 2013, 17:08

    Great!!
    Thanks :)

  • Neha 4 March, 2013, 12:33

    Thanks :)

  • yash 4 March, 2013, 14:52

    Add/Remove dynamic rows in HTML table

    function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var colCount = table.rows[0].cells.length;

    for(var i=0; i<colCount; i++) {

    var newcell = row.insertCell(i);

    newcell.innerHTML = table.rows[0].cells[i].innerHTML;
    //alert(newcell.childNodes);
    switch(newcell.childNodes[0].type) {
    case "text":
    newcell.childNodes[0].value = "";
    break;
    case "checkbox":
    newcell.childNodes[0].checked = false;
    break;
    case "select-one":
    newcell.childNodes[0].selectedIndex = 0;
    break;
    }
    }
    }

    function deleteRow(tableID) {
    try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for(var i=0; i<rowCount; i++) {
    var row = table.rows[i];
    var chkbox = row.cells[0].childNodes[0];
    if(null != chkbox && true == chkbox.checked) {
    if(rowCount <= 1) {
    alert("Cannot delete all the rows.");
    break;
    }
    table.deleteRow(i);
    rowCount–;
    i–;
    }

    }
    }catch(e) {
    alert(e);
    }
    }

    India
    Germany
    France
    United States
    Switzerland

  • abhishek awasthi 5 March, 2013, 12:43

    Hey can anyone point me how to add delete rows containing cascade dropdown list.

  • karthick 6 March, 2013, 18:23

    hi.. can u help me out?
    In
    Dynamically Add/Remove rows in HTML table using JavaScript ,
    i need a next button
    and when i click tat it should display the table again??

    pls help me ou t

  • Ravi 13 March, 2013, 20:58

    Thank you Patel, the code is really very useful.

    I thought after removing rows in deleteRow function, a “renumbering loop” would be nice.

    rowCount = table.rows.length;
    for(var i=0; i<rowCount; i++)
    {
    var row = table.rows[i];
    row.cells[1].innerHTML = i + 1;
    }

  • Surendra 17 March, 2013, 13:03

    Hi Viral,
    One more Nice Artical from so many.In above example you have shown how we can read values in PHP from multiple rows added there. But what if I want to read the same values in Spring controller through AJAX call. Please suggest.

  • soumya 19 March, 2013, 21:35

    i need to dispaly like this dynamically

    CB xxx M 06/06/2012
    CB xx M 05/10/1986

    I need two buttons and one to addSubscriber and another to addDependent
    on clicking on addSubscriber i need to add both subscriber & dependent as mentioned above . and addDependent should add the dependent to the subscriber

    Could you please tell how to proceed

  • Arafat 19 March, 2013, 23:28

    Hi, thanks for the post.

    Could anyone plz help me to put the values into database from the dynamically added rows???

    I am stuck with this.. Need urgent help…

    Regards,
    Arafat

  • Salin Hashma 28 March, 2013, 23:54

    Whene ever i am trying to add a row which have combo box the size of the combo box change in the next row any solution would be of great help

  • mayur agarwal 30 March, 2013, 14:26

    sir mine php code is not working.. my dynamic row data is not being saved to the database.

    please help….

  • Aamod tiwari 12 April, 2013, 14:29

    how to read parametar by servlet

  • diana 15 April, 2013, 14:13

    how ca i put it into database?????

  • johnRambo 26 April, 2013, 14:58

    How can i delete the row also from the database? Please help!!!
    Thanks in advance!!!!!!

  • sanajy 29 April, 2013, 11:07

    thanks man

    really this code help me lot.
    u r grrrrraaaaatttteeeee man

    thanks alot

  • mohiddin 6 May, 2013, 11:05

    im looking for this from 3days.i luv dis guy ummmammamaaaaa

  • Vishnu 6 May, 2013, 19:17

    Hi,
    I am beginner to PHP.
    It is very useful. thanxs a lot.

    When I insert into database. The last value only storing into database.

    Please give me the solution……..

    Thanx,
    Vishnu

  • swetha 10 May, 2013, 16:42

    please tell me how to display an existing excel sheet as web page which is editable

    • swetha 10 May, 2013, 16:44

      using java

  • Satish Kommineni 10 May, 2013, 17:04

    This code is not a complete one.
    when the row is deleted, there will be a problem with indexes.

    below are the steps:
    1. create a global variable – counter.
    2. when ever the row is added, increment the counter value.
    3. when ever the row is deleted, decrement the counter value and assign back the indexes

    var LWCOUNTER = 0;
    function addgoalRow(tableID) {
    var table = document.getElementById(tableID);
    var row = table.insertRow(table.rows.length);
    LWCOUNTER = LWCOUNTER + 1;
    ………………………………………………..

    function delgoalRow(tableID)
    var n=0;// assumes ID numbers start at zero
    ………………………………….
    if (chkBox.checked) {
    table.deleteRow(n+1);
    LWCOUNTER–;
    }else{
    chkBox.id = ‘lastWeekGoals['+n+'].isChecked’;
    chkBox.name = ‘lastWeekGoals['+n+'].isChecked’;
    ++n;
    ………………………………………………………….

    Any one wants the full code send an email to satish.kommineni@gmail.com

  • Satish Kommineni 10 May, 2013, 17:07
    function delgoalRow(tableID){
    	var table = document.getElementById(tableID);
    	var rowCount = table.rows.length;
    	var n=0;// assumes ID numbers start at zero	
    	var counts=rowCount-1;
    	var isAtleastOneChecked = 0;
    	for (var i =0;i&lt;counts;i++){
    		var chkboxAlert=&quot;lastWeekGoals[&quot;+i+&quot;].isChecked&quot;;	
    	    if(null != document.getElementById(chkboxAlert)  &amp;&amp; document.getElementById(chkboxAlert).checked)	{
    		   	isAtleastOneChecked = isAtleastOneChecked + 1;        	 
             }		  
    	}
    
    	if (isAtleastOneChecked &lt; 1){
            alert(&#039;No Row selected for Last Weeks Goal deletion.&#039;);
            return false;
         }
    
    
    	//Ist row is header, we need to ignore.Checkbox starts with 0	
    	for (var i =0;i&lt;counts;i++){		
    		var chkBox = document.getElementById(&#039;lastWeekGoals[&#039;+i+&#039;].isChecked&#039;);
    		var goalTextBox = document.getElementById(&#039;lastWeekGoals[&#039;+i+&#039;].goal&#039;);
    		var dueDateTextBox = document.getElementById(&#039;lastWeekGoals[&#039;+i+&#039;].dueDate&#039;);	
    		if (chkBox &amp;&amp; goalTextBox &amp;&amp; dueDateTextBox) {
    				if (chkBox.checked) {
    					table.deleteRow(n+1);
    					LWCOUNTER--;				
    	   			 }else{
    	   				chkBox.id 			= &#039;lastWeekGoals[&#039;+n+&#039;].isChecked&#039;;
    	   				chkBox.name 		= &#039;lastWeekGoals[&#039;+n+&#039;].isChecked&#039;;
    	   				goalTextBox.id 		= &#039;lastWeekGoals[&#039;+n+&#039;].goal&#039;;
    	   				goalTextBox.name 	= &#039;lastWeekGoals[&#039;+n+&#039;].goal&#039;;
    	   				dueDateTextBox.id 	= &#039;lastWeekGoals[&#039;+n+&#039;].dueDate&#039;;
    	   				dueDateTextBox.name = &#039;lastWeekGoals[&#039;+n+&#039;].dueDate&#039;;
    		    		++n;
    				}	
    		}			
    	}  
    	
    }
    
    
    
    
    
    
    function addgoalRow(tableID) {
    	
    	
        var table = document.getElementById(tableID);
        var row = table.insertRow(table.rows.length);
        LWCOUNTER = LWCOUNTER + 1;   
        var counts=LWCOUNTER;    
    
        
        var cell0 = row.insertCell(0);
        var isChecked = document.createElement(&quot;input&quot;);
        isChecked.type = &quot;checkbox&quot;;
        isChecked.name=&quot;lastWeekGoals[&quot;+counts+&quot;].isChecked&quot;;   
        isChecked.id=&quot;lastWeekGoals[&quot;+counts+&quot;].isChecked&quot;;  
        isChecked.style.bgColor=&quot;#D6F9B9&quot;;
        cell0.style.bgColor=&quot;#D6F9B9&quot;;
        cell0.bgColor=&quot;#D6F9B9&quot;;
        cell0.appendChild(isChecked);
    
        
        var cell1 = row.insertCell(1);
        var goal = document.createElement(&quot;input&quot;);
        goal.type = &quot;text&quot;;
        goal.name=&quot;lastWeekGoals[&quot;+counts+&quot;].goal&quot;;
        goal.id=&quot;lastWeekGoals[&quot;+counts+&quot;].goal&quot;;
        goal.size=35;
        goal.maxLength=250;
        cell1.appendChild(goal);
    
        var cell2 = row.insertCell(2);
        var dueDate = document.createElement(&quot;input&quot;);
        dueDate.type = &quot;text&quot;;
        dueDate.name=&quot;lastWeekGoals[&quot;+counts+&quot;].dueDate&quot;;
        dueDate.id=&quot;lastWeekGoals[&quot;+counts+&quot;].dueDate&quot;;
        dueDate.value=&#039;MM/DD/YYYY&#039;;
        dueDate.size=11;
        dueDate.maxLength=10;
        cell2.appendChild(dueDate);   
    
       }
    
    

     This Week’s GoalsDue Date

  • Edward 14 May, 2013, 1:03

    If anyone is having trouble with this script miscounting and you want it to ignore or other this might help. I have noticed your demo also has this problem… this should fix it.

    Notice the tags wrap around the tags that you need counting. Also name=”txtbox[]” is excluded on the first row so that needs to go in manually.

    
    <div id='ctrl_container'>
    
        <input type="button" value="Add Row" onclick="addRow('dataTable')" />
        <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
     
    <table id="dataTable"  border='0' cellspacing='0' cellpadding='0' > 
        
            <tr>
                <th> Select </th>
                <th> ID </th>
                <th> Question </th>
            </tr>
        <tbody>
            <tr>
                <td> <input type="checkbox" name="chk"/> </td>
                <td> 1 </td>
                <td> <input type="textarea" name="txtbox[]"/> </td>
            </tr>
        </tbody>
    </table>
    
    </div>
    
    
    
        <script language="javascript">
            function addRow(tableID) {
     
                var table = document.getElementById(tableID);
    
                var rowCount = document.getElementById(tableID).getElementsByTagName('tbody')
                [1].getElementsByTagName('tr').length;
                var row = table.insertRow(rowCount +1);
     
                var cell1 = row.insertCell(0);
                var element1 = document.createElement("input");
                element1.type = "checkbox";
                element1.name= "chkbox[]";
                cell1.appendChild(element1);
     
                var cell2 = row.insertCell(1);
                cell2.innerHTML = rowCount + 1;
     
                var cell3 = row.insertCell(2);
                var element2 = document.createElement("input");
                element2.type = "textarea";
                element2.name = "txtbox[]";
                cell3.appendChild(element2);
     
            }
     
            function deleteRow(tableID) {
                try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
     
                for(var i=0; i<rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if(null != chkbox && true == chkbox.checked) {
                        table.deleteRow(i);
                        rowCount--;
                        i--;
                    }
     
     
                }
                }catch(e) {
                    alert(e);
                }
            }
     
        </script>
     
  • Edward 14 May, 2013, 1:05

    EDIT:

    If anyone is having trouble with this script miscounting and you want it to ignore the

     <th> or <tr> 

    tags or other this might help. I have noticed your demo also has this problem… this should fix it.
    Notice the

     <tbody> 

    tags wrap around the tags that you need counting. Also name=”txtbox[]” is excluded on the first row so that needs to go in manually.

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]