Dynamically Add/Remove rows in HTML table using JavaScript
- By Viral Patel on March 16, 2009
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.

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
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
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.
Get our Articles via Email. Enter your email address.
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.
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>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.--> <?php echo ""; ?> No. ContactName ContactNumber 1 $b) { foreach($txt2 as $c => $d) { echo $txt1[$a]; echo $txt2[$c]; } } } ?>Well Done Viral.. Saved me lots of time!! Thanks and God bless!!
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
Hi Viral,
how do we validate a form(dynamic table of rows) using javascript,if you could provide that tutorial it would be great
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.
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
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
thank you for the script! 100% useful
This is awesome.
Thank you.
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?
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
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
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.
This code only works in Firefox and does not work in IE
This code too works for the IE i have tried it in my application
Just saying thanks. Helped me a lot.
I am Brazillian. How I get all values of table?
thanks a lot, it’s really a good code working well,.
can you please provide us the way to access the dynamically generated row data in jsp, Thanks in advance.
how can I set the size of a text input within a new row?
its really good code, i used it for diffrent requirement thanks…. a … lot
I LOVE YOU! Thanks for this tutorial!
It does not colspan
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?
Good one ,nice tutorial….
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 = 'pubNum&# 039; + x; alert( 'name is' + newcell.childNodes[0].name); break; } } }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
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);I’m also facing this problem! Can anyone solve it?!
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.
how can I retain that dynamically created text boxes’ values on button click?
thanks in advance,
demo
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.
Thank you very much for your code.
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
patel,
thx alot for your helpful script.
wish you always success in every of your activities.
rgds,
maman
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
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..
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.
How To Add/Remove rows from table having Drop Down List, that have the values retrieving from database
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?
thanks a million for the code
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.
@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.
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…
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?
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 ?
Thanks for the bit about inserting table rows with Javascript. Super helpful!
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<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
Thanks