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,
your code fruitful for the me ..but i am not able to get the values dynamic created controls BY Classic ASP, Please help me to find out
I,ve done the same thing as you told i.e putting [ ] after the names. When i hit the submit button, I am getting in the other form, i’m getting only the first value, and moreover it is showing that the array length is 1.
I
Thanks a lot.
This helped a lot. Yes – a lot!
Could you please help on a little thing…
What I am doing is… I am using Autocomplete on the first textfield in the row.
I have successfully toggled the id of that field so all fields get a unique id for the jquery autocomplete to work as below
newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(‘id=”exampassed1″‘, ‘id=”exampassed’+rowCount+’”‘);
where exampassed1 is the first field present on pageload – the one which is copied…
now I am getting the fields properly but the autocomplete is not working…
seems like jquery needs these to be present on pageload… any chance we can poke the jquery to tell that we have added a new field…
many thanks!
Hello,
Great Code…! Thanks i get a lot of ease from this…! Thanks again..!
hi viral,
good morning…
very good coding u done…
thanks u r helping students like me…by u r idea..
i m doing a Pathalogy Lab managment project for tybcs year2010-2011
but i have a problem as how i can add the checkboxes which takes the value from database & shows the no of corresponding checkboxes into the current form only.ie in second column only.
i m doing it in jsp with oracal as database.
please help me as early as possible….
what is the difference between Arrays.sort() and Collections.sort()
In Real Time which sorting technique is used and also searching
how to get values in the textbox…..plz reply me
Thanks a lot… I really help me on my study.
But, how about if I need to place more than one table in a form? Since it will create a same name for each control in tables. And if click the add new row button on table two, it will add a new row to table one or a table that has a name described in the js file.
Would you please give help again with this? Please email me if you would.
Hey Viral, nice script!
It is exactly what i was looking for!
Thanks a lot for the post!
Hi Viral,
How can i change the first code to get the name of the input like name=”text[ ]“?
Thanks!
Want to develop a php script to generate report having option pdf,xls and csv using php mysql.
Help….
Hello,
Your code is great!!
But No multiple values getting stores for diffrent text boxes..Solution is needed
Hi viral,
This is definately a very useful tutorial. One part I am puzzled with is how do I read the data in the dynamic elements created.
Suppose I only want to be able to delete the row if the conent text does not equal “Testing”. Basically I am having diffculty trying to read the value in the dynamically created rows.
Please help
regards
Shuel
thnx..nice code..
but i have one doubt…
assume that i created dynamically three rows but how to store the values in db, i m using form bean and how to get these values dynamically…plz explain..
sir plz send me insert code how can insert value into database
when i add more rows then value should be add into database
thanks for this nice code
hi viral would you kindly give me some instructions on how to process computation on each row of the table(using javascript) if not PHP..Im currently making a purchase order..Although I have a code it only computes the first row of the table..any help is appreciated..thanks
@Billy – I am not sure what kind of computation you intended to do. You may have a look to this tutorial http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html where the sum is performed for all the values.
This code doesnt work on IE.
Any help plz?
Thx!
Thank you so much it is very very helpful
hi,
am trying this code. its working good. But am trying to validate the form using javascript i get error. how to validate these type of dynamic forms? and how to give the name for particular filed in dynamic? Please any one give me a solution.
Thanks
muthu
HI Viral
Thx u, that code is i need ^_^
How to add events and assign functions to dynamically created rows in a table.
I am trying to populate a textbox in the same row as the drop down list with the selected value and i just cant figure it out coul you please show ho to do this
Hi Viral,
This is my HTML code:
1
This is my Servlet coding:-
try {
String[] nam = request.getParameterValues(“add”);
out.println(nam.length + “”);
for(int i = 0; i < nam.length; i++){
out.println(nam[i] + "”);
}
}catch(Exception ex){
out.println(ex);
}
This coding shows my java.lang.NullPointerException.
Please help me how to get data submitted by this form on my Servlet Page.
Thanks
Shams
Thanks Viral
I have done it. I just added
element2.name = “add”;
in javascript coding.
Thanks for this post
Shams
Hi,
Its not working for keep on click Add Row button and keep on click Delete Row, its some times two rows deleted….
Thanks,
bhushanam.
Thanks for the code; it simply reduced my work
hi viral,
this tutorial was truely helpful, cos of this i was inspired to go through entire html dom tutorial of w3schools, all thanks to your tutorial. i tried to play around with this code and got stuck. pls help me solve it. what i did is, i included …. before the input as header for each column. now when i try to add row, nothing happens, i tried using 2 for loops, one for row another for column, i could get a single cell but, nothing appeared within it(no chkbox, no text field nothng) and only one cell appeared below the checkbox. code of for loop is as below:
for(var j=1; j<=rowCount; j++) { for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i)(j); newcell.innerHTML = table.rows[1].cells[i].innerHTML; } }pls point out where am i going wrong..
thanks a ton
hey viral,
i found the solution, thanks for the tutorial,
for ppl who have issue similar to me, in the code it is rows[0] within for loop, i changed it as below.
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
please ignore my last comment. i was trying in entirely different direction using two for loops using 2 dimension array logic ha ah ahaha…
thanks viral once again..
Hi Viral,
Great Script and tutorial !
I have a question and any help is greatly appreciated:
Let’s say three rows are populated with data.
when the “Reset” button is clicked, the event deletes only the first row data and leaves the succeeding rows data intact.
How do I ensure that all data is flushed upon hitting “Reset” button?
Thanks in advance.
Thanks a lot Viral!! This solution helped me a lot!!
_hi
_thank for your tutorial. how would i be able to submit several rows at once using php with the rows having been added using javascript?
@slim – check the above example of getting values in PHP
thanks for the great code
But can’t add the more values in database.
plz help
hiiiii
your code is nice but I’m not getting how to store the field values into the database using this code.
The main problem is how to insert the multiple values into the database using text box.
I’ve created a table called “STOOL” in that there are 7 field namely “AUTHOR,ARTICLE,JOURNAL,IMPACT_FACTOR,ABSTRACT,ADDRESS and YEAR”
Here if suppose more than 1 author published the same article how to insert the more than one author name into the database????????????
using text box after pressing the submit button it should store in database.
CAN ANY ONE GIVE THE CODE FOR THIS PROBLEM PLZ…………-:(
Hi Viral,
I have a set of radio buttons ( for Yes and No ) and let’s say one of the buttons is checked.
When a new row is added, the checked button shows up in the new row.
By default, neither Yes nor No is checked.
Please look at the example code below:
In the addRow method, I have added the type ‘radio’ to the switch:
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;
case “textarea”:
newcell.childNodes[0].value = “”;
break;
case “radio”:
newcell.childNodes[0].checked = false;
break;
}
and here’s the html markup for the radio buttons:
Yes
No
Inspite of adding the type radio and disabling any checked radio-buttons, the buttons carry over their checked status to the next row.
Can you please let me know of a way to resolve this issue.
Appreciate your help and thanks in advance.
Keep up the great work
Oh Boy – seems like the html markup is not going thru. I’ll try again with < and >:
<td >Yes<input id=”b1″ type=”radio” name=”decider[]” value=”y” />
No<input id=”b2″ type=”radio” name=”decider[]” value=”n” />
</td>
I hope this one goes thru.
Please helps me regarding validation of “Add/Remove rows from table having Drop Down List”
2nd one.
If i add button is clicked I can validate only first id.
I want mandatory of all added rows.
Please helps me
Many thanks
hi,
i am trying to add input type file dynamically but i not able to do this using this script
Hi
great job its more help full to me but
the above code is not correct to my my requirements please help any one
1) sr.no is not properly assigned ,2nd valued row is not coming.directly 3rd row is coming after 1st row.
2)when ever i delete the any row the sr.no should not be rearranged
hi
i used your js script to add/remove elements thank you for this post it was very helpfull
but i have a problem to modify it
in fact i’d like to be able to add a row in the midle of the table
for exemple i create line 1,2,3
and the i’d like to add a line between the line 2 and the line 3
can you please help me doing this
thank you
regards
Hi,
I need your help in one issue which i am facing.
Assume i have a 10 rows in one table in my jsp.
Each row has a set of 3(Up,Down,NA) radio buttons.User’s can select each radio button in a row and there is a submit button at the bottom.
At the click of the submit button i need to update all the rows for which there is a change in the radio button value.
I know how to update one row at a time, but how do i update only those which are selected.
Hope you to get a reply from you.
please let me know if you need more information.
Regards,
Irfan
i want to append written comments, like how we write status or comments in facebook and in thi s site,to existing jsp file.
and the file should append contents and not replace them.
Has anyone use this successfuly using jquey ui autocomplete? autocomplete code works fine on first row, but when you add a new row autocomplete doesnt work. what i’ve read so far, its seems like autocomplete code should be called when adding the new row, the thing is im not quite sure how to do this….. thanks..
Hi,
Thanks for your excellent tutorial, i always find it better to loop from the row count downwards because then you can get rid of the rowcount– and the i–.
for (i = rowCount – 1; i > -1; i–)
{
var myRow = myTable.rows[i];
var myCheckBox = myRow.cells[0].childNodes[0];
if (myCheckBox.checked)
{
myTable.deleteRow(i);
}
}
This is a great article. However, I have a question. can’t you simply use createElement and appendElement with a specific innerHTML?
Tnx
Thanks for your nice example
Hi Viral,
Thanks for your code. I have names for input as follows:
Now, when I submit the form in firefox/chrome only the first row is sent through the POST variable whereas, when i submit the form in IE, all rows are passed.
What could be the problem?
Thanks in advance
Is there any way to add an input box where the user specifies the amount of rows he wants to add? The default value can be 1 so that clicking on add row would default to adding 1 row.
Hi Viral,
how can I add the ability for a user to enter a number and that will in turn add the amount of rows? If user enters 5 and clicks on add row, it should be 5 rows.
Regards
Gino
Please disregard. I figured it out.
PS: Apologies for the 2x post.
Gino