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

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
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.
Thanks dear ……ur awesome
Great!!
Thanks
Thanks
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
Hey can anyone point me how to add delete rows containing cascade dropdown list.
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
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;
}
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.
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
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
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
sir mine php code is not working.. my dynamic row data is not being saved to the database.
please help….
how to read parametar by servlet
how ca i put it into database?????
How can i delete the row also from the database? Please help!!!
Thanks in advance!!!!!!
thanks man
really this code help me lot.
u r grrrrraaaaatttteeeee man
thanks alot
im looking for this from 3days.i luv dis guy ummmammamaaaaa
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
please tell me how to display an existing excel sheet as web page which is editable
using java
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
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<counts;i++){ var chkboxAlert="lastWeekGoals["+i+"].isChecked"; if(null != document.getElementById(chkboxAlert) && document.getElementById(chkboxAlert).checked) { isAtleastOneChecked = isAtleastOneChecked + 1; } } if (isAtleastOneChecked < 1){ alert('No Row selected for Last Weeks Goal deletion.'); return false; } //Ist row is header, we need to ignore.Checkbox starts with 0 for (var i =0;i<counts;i++){ var chkBox = document.getElementById('lastWeekGoals['+i+'].isChecked'); var goalTextBox = document.getElementById('lastWeekGoals['+i+'].goal'); var dueDateTextBox = document.getElementById('lastWeekGoals['+i+'].dueDate'); if (chkBox && goalTextBox && dueDateTextBox) { if (chkBox.checked) { table.deleteRow(n+1); LWCOUNTER--; }else{ chkBox.id = 'lastWeekGoals['+n+'].isChecked'; chkBox.name = 'lastWeekGoals['+n+'].isChecked'; goalTextBox.id = 'lastWeekGoals['+n+'].goal'; goalTextBox.name = 'lastWeekGoals['+n+'].goal'; dueDateTextBox.id = 'lastWeekGoals['+n+'].dueDate'; dueDateTextBox.name = 'lastWeekGoals['+n+'].dueDate'; ++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("input"); isChecked.type = "checkbox"; isChecked.name="lastWeekGoals["+counts+"].isChecked"; isChecked.id="lastWeekGoals["+counts+"].isChecked"; isChecked.style.bgColor="#D6F9B9"; cell0.style.bgColor="#D6F9B9"; cell0.bgColor="#D6F9B9"; cell0.appendChild(isChecked); var cell1 = row.insertCell(1); var goal = document.createElement("input"); goal.type = "text"; goal.name="lastWeekGoals["+counts+"].goal"; goal.id="lastWeekGoals["+counts+"].goal"; goal.size=35; goal.maxLength=250; cell1.appendChild(goal); var cell2 = row.insertCell(2); var dueDate = document.createElement("input"); dueDate.type = "text"; dueDate.name="lastWeekGoals["+counts+"].dueDate"; dueDate.id="lastWeekGoals["+counts+"].dueDate"; dueDate.value='MM/DD/YYYY'; dueDate.size=11; dueDate.maxLength=10; cell2.appendChild(dueDate); }This Week’s GoalsDue Date
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>EDIT:
If anyone is having trouble with this script miscounting and you want it to ignore the
tags 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.