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";
			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";
			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.



256 Comments

  • karthik wrote on 11 May, 2011, 21:00

    Hi viral,

    The code given by you was superb. Since am very new to this Javascript/html, it helped me a lot. i have one problem while using this code, after creating a table if i am clicking on referesh/back button, the created table is gone. but i need it to be a static one. Could you please help me how to display a dynamic table in static manner.

  • MD wrote on 12 May, 2011, 11:51

    Hello Sir,
    First Of all Thanks For This Much Nice Code On Dynamic Row Creation And Input box Creation.
    I Modify Your Code As I Wont Three Input Box In One Row Ex. (no, ContactNm, Number )

    Now Problem Is That I Want To Get Value Of All The Text Box (Approx 20 25 Rows)
    I Tried A lot To Ge Value Using Following Code But Failed.

    I hope You Will Help Me.
    If Possible Send Me Mail As I Am Just New To This Field
    And I Have To Complete My Work In Fix Time.

    Please Note That I Have Changed JS code So Check It Properly.

    Thanks A Lot.

    My Code:(Also Yours)

    		//fUNCTION TO ADD ROW.
    		function addRow(tableID)
    		{
    			var table = document.getElementById(tableID);
    			var rowCount = table.rows.length;
    			var row = table.insertRow(rowCount);
    
    			if(rowCount%2)
    			{
    				row.bgColor = '#FFFFFF';
    			}
    
    			else
    			{
    				row.bgColor = '#D6D6D6';
    			}
    			var cell2 = row.insertCell(0);
    			cell2.innerHTML = rowCount + 0;
    
    			var cell3 = row.insertCell(1);
    			var element2 = document.createElement("input");
    			element2.type="text";
    			element2.name="txt1[]";
    			cell3.appendChild(element2);
    
    			var cell3 = row.insertCell(2);
    			var element3 = document.createElement("input");
    			element3.type="text";
    			element3.name="txt2[]";
    			cell3.appendChild(element3);
    		}
    
    		function deleteRow(tableID)
    		{
    			var table = document.getElementById(tableID);
    			var rowCount = table.rows.length;
    			if(rowCount&gt;1)
    			{
    				table.deleteRow(rowCount-1);
    				rowCount--;
    			}
    		}
    
    <!-- JavaScription Function Over. -->
    
    <!-- Table Start For Dynamic Row Creation. -->
    
    <b>
    Add Or Remove Row:
    <!-- Button To ADD Row.-->
    
    <!-- Button To Delete Row.-->
    
    &lt;?php
    echo &quot;";
    ?&gt;
    
    		No.
    		ContactName
    		ContactNumber
    
    		1
    
     $b)
    	{
    		foreach($txt2 as $c =&gt; $d)
    		{
    			echo $txt1[$a];
    			echo $txt2[$c];
    		}
    	}
    }
    ?&gt;
    
  • Anirban wrote on 21 May, 2011, 18:57

    Well Done Viral.. Saved me lots of time!! Thanks and God bless!!

  • Aany wrote on 26 May, 2011, 15:08

    Hi,
    You know you just saved me a lot of time. I just started using javascript and i was really lost in all the tutos for creating tables and datagrids. But your code is really easy to understand and I am really grateful to you.
    Aany

  • Deepak wrote on 5 June, 2011, 17:32

    Hi Viral,
    how do we validate a form(dynamic table of rows) using javascript,if you could provide that tutorial it would be great

  • Prabakaran wrote on 9 June, 2011, 16:46

    Hi
    This above code is nice and thanks for that. But I am not able to enter date in a text box by calender which is available near to text box. Please help me out.. very urgent.

    Thanks
    Prabakaran K.

  • Ashafak wrote on 18 June, 2011, 17:28

    Dear Viral;
    Thanks for nice script . I used it for dynamic data entery purpose however i have one problem. My first field is text box with a counter . I want that every time user add a row the new row’s first text box come with updated counter value .
    Thanks

  • muthu wrote on 6 July, 2011, 9:43

    I used for Dynamic Add Row in Javascript ,How Can Get Value in Database and assined Value in Multipel Row in Text box or Dropdown

  • jinxx wrote on 19 July, 2011, 21:49

    thank you for the script! 100% useful

  • capetownct wrote on 20 July, 2011, 14:39

    This is awesome.
    Thank you.

  • FELIPE wrote on 25 July, 2011, 3:07

    how can you add radiobuttons ??-.. when i use the same name for the array obviously all of the radiobuttons get modified.. how can this be done?

  • String wrote on 27 July, 2011, 9:08

    Hi Viral this is a very good Tutorial for begineer like me .i just want to know how to validate this Dynamically added Gridview in Jsp page? please provide me any sample code for that!

    Thanks in Advance

  • neeraj wrote on 5 August, 2011, 16:07

    Hi viral,
    This is great code man.
    But i”m stuck at php side. I copied the code exactly posted by you. When I submit the form form html, In php I get the values only for the first row and not for the values of the row added dynamically. I saw, some one faced similary problem and then he solved the problem after added a name attribute for the new element. Though It seems the name is already there for the newly created form elements. I tried all but not successful.

    Can you please help me out

  • farha wrote on 14 August, 2011, 3:02

    Thanx the code was superb…but please tell me I want to add cells of specific size because my table has textbox of specific size inserted in a cell based on the data it will hold.Please how to do this.Thanks in advance.

  • zabiholah abedini wrote on 19 September, 2011, 10:58

    This code only works in Firefox and does not work in IE

    • rachel wrote on 30 September, 2011, 16:36

      This code too works for the IE i have tried it in my application

  • Rodrigo wrote on 20 September, 2011, 1:08

    Just saying thanks. Helped me a lot.

  • Marcos Arantes wrote on 29 September, 2011, 0:42

    I am Brazillian. How I get all values of table?

  • sivakumar wrote on 23 October, 2011, 19:23

    thanks a lot, it’s really a good code working well,.

  • sivakumar wrote on 23 October, 2011, 19:24

    can you please provide us the way to access the dynamically generated row data in jsp, Thanks in advance.

  • madmin wrote on 27 October, 2011, 2:45

    how can I set the size of a text input within a new row?

  • Sathisha N M wrote on 8 November, 2011, 19:36

    its really good code, i used it for diffrent requirement thanks…. a … lot

  • Ben wrote on 10 November, 2011, 11:21

    I LOVE YOU! Thanks for this tutorial!

  • Ali wrote on 12 November, 2011, 7:54

    It does not colspan

  • Aniket Yevalkar wrote on 18 November, 2011, 16:25

    Hi…nice code…I am using this code…but can we add the elements of new rows in an array?
    Actually I use this code and generate 5 rows…then I call a form action and validate the contents of rows..but when validation fails then I m redirecting to same page….during this time the dynamically created rows are not preserved(also the values that I put in text boxes)…How can I preserve these controls…any suggestions?

  • rakesh wrote on 5 December, 2011, 13:25

    Good one ,nice tutorial…. :-)

  • Loi Le wrote on 6 December, 2011, 0:19

    Hi Viral,

    I am using your example for a program I am working on. I encountered a problem, and I am hoping you could assist. For the dynamic drop-down list, how can I tweak the code so that I can have multiple drop-downs? My program has 2 drop-downs, and 1 textbox. I don’t think the switch method would work because I need the two drop-downs to have different element name. Below is a snippet of what I have.

     var x = 0;
    
    function addRow(tableID) {
    
        x += 1;
    
        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;
    
            switch (newcell.childNodes[0].type) {
            case "text":
                newcell.childNodes[0].value = & quot; & quot;;
                newcell.childNodes[0].name = & #039;qty&# 039; + x;
                break;
            case "checkbox":
                newcell.childNodes[0].checked = false;
                break;
            case "select-one":
                newcell.childNodes[0].selectedIndex = 0;
                newcell.childNodes[0].name = &#039;pubNum&# 039; + x;
                alert( &#039;name is&#039; + newcell.childNodes[0].name);
                break;
    
            }
        }
    
    }
    
    • Viral Patel wrote on 6 December, 2011, 0:40

      Hi Loi Le,
      The above javascript works for any number of select boxes. You just have to add these select boxes in your html table and the js will automatically render it to the newly added row. See here is example where two select boxes are rendered: http://jsbin.com/ugivef/edit#javascript,html,live

      • Loi Le wrote on 6 December, 2011, 18:57

        Viral,

        Thanks for the quick reply. I understand that the switch will create multiple drop-down. My problem is assigning different names for each drop-down so that I can insert the values into a database. I am programming in coldfusion (no knowledge of asp or php). The switch method would assign the same name for all drop-downs. The 1st snippet below shows how I assign the name. If I have two drop-downs, they would both be called pubNumX. Is there another way to insert multiple drop-downs without using the switch? The second snippet is what I’m trying, but it doesn’t work. Thank you for your time and assistance.

        snippet 1:

        case "select-one":
               newcell.childNodes[0].selectedIndex = 0;
        	   newcell.childNodes[0].name = 'pubNum' + x;
        

        *******************************
        Snippet 2:

        var x = 0;
        function addRow(tableID) {
        x += 1; 
        
        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";
        cell1.appendChild(element1);
        
        var cell2 = row.insertCell(1);
        cell2.innerHTML = table.rows[0].cells[1].innerHTML;
        cell2.name = 'pubNum' + x;
        var element2 = document.createElement("input");
        element2.type = "select";
        cell2.appendChild(element2);
        
        var cell3 = row.insertCell(2);
        cell3.innerHTML = table.rows[0].cells[2].innerHTML;
        cell3.name = 'pubFormat' + x;
        var element3 = document.createElement("input");
        element3.type = "select";
        cell3.appendChild(element3);
        
        var cell4 = row.insertCell(3);
        cell4.innerHTML = table.rows[0].cells[3].innerHTML;
        cell4.name = 'qty' + x;
        var element4 = document.createElement("input");
        element4.type = "text";
        cell4.appendChild(element4);
        
        • Judy wrote on 8 December, 2011, 11:31

          I’m also facing this problem! Can anyone solve it?!

  • Maurice Ben-Oduro wrote on 10 December, 2011, 3:04

    Thank you very much for the line of code! A huge time saver! Is there any way to allow the selection to populate into another box. For instance… If I select Sweden from the box then a link will popup for me to select.

  • demo wrote on 16 December, 2011, 21:48

    how can I retain that dynamically created text boxes’ values on button click?
    thanks in advance,
    demo

  • Prateek Joshi wrote on 20 December, 2011, 13:33

    just like this. last column of my row contains the add more and delete buttons.
    on clicking add more, a new row with these buttons should come up and remember that buttons from earlier row should get removed.

  • Mohan wrote on 28 December, 2011, 17:47

    Thank you very much for your code.

  • Rock wrote on 28 December, 2011, 18:04

    Hi,How to generate multiline textbox or textarea using javascript and add or remove it dynamically
    I tried but it is not working in IE

  • maman wrote on 30 December, 2011, 13:42

    patel,
    thx alot for your helpful script.
    wish you always success in every of your activities.
    rgds,

    maman

  • Mahmud wrote on 1 January, 2012, 13:10

    I just want thanks and Happy new year to you, Viral..its just amazing and simple code.. I have encountered a problem here while I want of insert the value of the multiple text field to Mysql table only first text value is inserted while checkbox field is inserted as “on”, Please help to insert all the text field value I want. I think there is problem with for each statement.. thanks and a great year ahead

  • Divya wrote on 2 January, 2012, 17:22

    Good Evening

    Which is very use full for me but i want that rows datas should be insert in sql table..Am trying but i had to insert the first records values only..

  • raghavendra wrote on 4 January, 2012, 11:45

    dynamically adding of rows in a table is working fine.. but i want to delete the rows without the help of checkboxes. i mean i want to delete the last row which was previously added. could u pls help me out in this approach as i’m new bie in javascript.

  • rajalakshmi wrote on 7 January, 2012, 12:59

    How To Add/Remove rows from table having Drop Down List, that have the values retrieving from database

  • sumi wrote on 14 January, 2012, 0:48

    hi viral,

    thanks for the useful code.

    I would like to add header row for each column. can you help me how to add it?

  • Jagan wrote on 14 January, 2012, 16:38

    thanks a million for the code

  • harry wrote on 15 January, 2012, 19:10

    hi viral
    i m having the problem with this code when i click on addrow button a row is added but i have to go back to see it .and on clicking any other button (say submit) these are deleted .please help me .its urgent.

    • Viral Patel wrote on 16 January, 2012, 12:03

      @Harry: I didn’t get you. What do you mean by go back to see it? Also by clicking submit button, the page gets submitted to server side code. So you need to take care of painting the fields back when the page gets reloaded.

      • Riyas wrote on 26 January, 2012, 13:19

        Hi Viral,

        I have multiple rows in a table where each rows contains a delete button and a check box. Now i want to delete particular row when the user checks the checkbox field and click the delete button on that particular row. I tried your code (deleterow(datatable)) but it just delete the selected checkbox row when i used to click delete button on some another row. Please help me out…

  • ag wrote on 16 January, 2012, 20:14

    this code is great, is there a way to use the checkbox to tell the the “add row” button to insert the new row after the checkbox instead of at the end of the table?

  • raghu wrote on 19 January, 2012, 13:10

    foreach($txtbox as $a => $b) echo “$chkbox[$a] – $txtbox[$a] – $country[$a] “; code is returning only one row. it is not returing more than one row.

    any solution ?

  • Jeff wrote on 24 January, 2012, 2:27

    Thanks for the bit about inserting table rows with Javascript. Super helpful!

  • Abdul Basit wrote on 29 January, 2012, 23:52

    Thanks For the help It is very Useful code and working 100% correctly

    but some people need change the id and name also for this i make a change in the script take a look on the code

    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&lt;colCount; i++) {
    
                    var newcell = row.insertCell(i);
    
                    newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                    //alert(newcell.childNodes);
                    switch(newcell.childNodes[0].type) {
                        case &quot;text&quot;:
                                newcell.childNodes[0].value = &quot;&quot;;
                                break;
                        case &quot;checkbox&quot;:
                                newcell.childNodes[0].checked = false;
                                break;
                        case &quot;select-one&quot;:
                                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&lt;rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if(null != chkbox &amp;&amp; true == chkbox.checked) {
                        if(rowCount &lt;= 1) {
                            alert(&quot;Cannot delete all the rows.&quot;);
                            break;
                        }
                        table.deleteRow(i);
                        rowCount--;
                        i--;
                    }
    
                }
                }catch(e) {
                    alert(e);
                }
            }
    

    India
    Germany
    France
    United States
    Switzerland

    Thanks

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.