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

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 />"; ?>
Get our Articles via Email. Enter your email address.



Hello,
Please add your site at http://www.sweebs.com. Sweebs.com is a place where other people can find you among the best sites on the internet!
Its just started and we are collecting the best found on the net! We will be delighted to have you in the sweebs listings.
Regards
Kris
Thanks for this code, it came in handy.
A note for everyone else.
If you enclose a in a and try to set the innerHTML of the div to something else, it will not work in IE, but will in all other browsers.
Thank you Samir for valuable comment.
how do i display my entry?
Hi Erick,
I am not sure if I get you, but do you mean to display a cell element?
hi…i have a table with header and row of input. i want to insert new row when user click on Add More Item button. Have tried above code but not working. No javascript error but no row inserted, need your advise
hey.. superb code!! but how to call function on generated rows, for eg : onblur so on??
The row id can’t refresh.
I am trying to adapt your code so that this page
http://www.whatsfordinner.net/meals.html
on my site includes checkboxes so that suggested meals can be removed (and later replaced with other meals, but one step at a time). How can I reach you so that I can clarify a part of your code that I don’t understand?
@Jean: You can send me email at viralpatel [dot] net [at] gmail [dot] com.
Hey Viral,
Thank u very much..
I am having exact need for the same and i got it. AMAZE !!!
But I am having a problem.. I am using servlets and jsps in my application. Now can u suggest me any way by which i can get the values of those text boxes(which are dynamically generated by clicking ADD ROW) and i can enter those values in the database after clicking on submit button in the end !!!
Hoping for ur favorable reply…
Thanking You..
Hi Mihir,
You can get the values of textboxes generated dynamically by calling request.getParameterValues() method in your JSP/Servlet.
Suppose the name of the textboxes that you generate is “txtAddress” then you can just call
String [] addresses = request.getParameterValues("txtAddress");Hope this will solve your query.
Hey Viral,
Thanks for replying.. but its still not working… i think when we create elements at that time with declaring the type can we give a name to that element ?
I mean in a form the name of textfield is \"design\" and when we are creating a new textfield using createElement() at that time can we give name to that element ?
Hi Mihir,
You can add name to the newly added field by using setAttribute() method. For example:
element.setAttribute("name", "txtAddress");Once you provide the name to newly created element, it can be accessed from JSP by calling getParameterValues().
its still not done …. values of form are not stored in string[ ] ….
are u sure this is the way to get all values ….???
cos wen i check string[ ] it shows empty array ….
Hi Mihir,
I have using the same code and it is working for me.
Following is the JSP code that gets the request parameters and prints them.
<h2>Address</h2> <% String [] addr = request.getParameterValues("txtAddr"); for(int i=0; addr != null && i < addr.length; i++) { out.println(addr[i] + "</br>"); } %>I hope this helps and solves your problem.
this is a nice article …..keep it up
hye viral,
thanks for the helpful article of yours, been searching this for days. 10q.
now i’m able to add the rows, but i’m not sure on how to save those values in the dynamically added rows into the database.
can you please help me out in this…
*the question might sound same like mihir’s question, but i still dont understand the way that you have explained above as i’m just a beginner in programming.
thanking you in advance.
Hi Minie,
For adding these dyanmic generated records to the database, you have to write a server side code in any server side scripting language like JSP, PHP or ASP. And you have to iterate through request to get all the values and then you can insert these values to the database.
If you are still struggling to understand, send me an email at viralpatel [dot] net [at] gmail [dot] com.
hey viral
good job done
but i have a problem
In my table i have columns that has a drop down menu and i need to add it
do i require any server side programming
if yes plz send me the codes
else
send me the codes
in the code part when a element is created i have used “select” in place of “input”
and “name” in place of type.
hey viral
Good job.
It helped me a lot.
But i have the same problem that Rakesh had.
In my table i have columns that has a drop down menu .How to make this column repeated.
Also in [element2.type = \"text\"; ] it is taking only text and checkbox. For date and number type this doesnt work
How to make the fields with date and number type repeated.
Also i want a Date field in my column such that when i click that column calender is pop up.how to do that
Hi Rakesh / Raj, I have updated the article and added the case where a table will have drop down list. Check the code and let me know if you have any doubt.
Hi Viral,
Thanks a ton for your help.
Its working fine.
Still if i change the type of the column to number or date.this doesnt work.
Also when i delete the row the Sr No. of rows is not refreshed.
how to do this thing?
Also how to populate a calaneder in the date field?
Hi viral,
Thanks a ton for your help.
This is working file.
But still i have a problem that when i change the column type to number or date this doesnt work.
Also the Sr. No. of the rows is not refreshed when we delete a row.
Please look into this.
Thanks
Hi Raj,
I dont get you. How can you change column type in HTML table to number or date!!! I think you are using some calender control in your table and you want to replicate it!. If you learn simple DOM manipulation it will be easy for you to implement such requirements. I will suggest you first to do some handson on JS DOM. This may help you.
Hi Viral,
I use your code and this is what i looking for. But I have question, Is\\\’t possible to Add additional Drop down after you select the first drop down the second drop down filled the cities? For example if you select \\"United States\\" all Cities under United Sates must filled the second drop down. Thanks in advance.
hi Very nice
i\\\’m using this code.. but i want one more sol.how to get (Click button)dyamic table row value..
Hi Viral ,
i wanted to say that when i delete a row the Serial no. of all the rows are not refreshed.
For e.g if Sr.no. are 1,2,3,4,5,6,7,8,9 and i delete the 5th row then the serial no. should be from 1 to 8 but the sr.no.that comes on the html atre 1.2.3.4.6.7.8,9.
How to modify the delRow method for this
hey thankyou so much keep the good work
hello Viral,
Nice work. thanks for uploading code like this. but i have a problem that how can i use this code in PHP. plz reply. thx.
bye
hello Viral,
its have not a heae line like the below:-
Item qty
————–
a 1
b 2
if possible please add the head line.
Best Regards,
Vilart
hey thanks i have ued your code so it was very use full to me.
I tried the code and deployed it in tomcat server using eclipse IDE
The code doesnt work.
It shows no error but no action takes place.
Can anyone help me solve the problem?
var rownumber = -1;
function addRow(event, tableID) {
var srcElem = document.all ? event.srcElement : event.target;
while(srcElem.tagName != “TR”)
{
srcElem = srcElem.parentNode;
}
rownumber=srcElem.rowIndex;
var table = document.getElementById(tableID);
var count = document.getElementsByName(“country”);
var rowCount = table.rows.length;
var colCount = table.rows[rowCount-1].cells.length;
if(rowCount==rownumber+1)
{
//FOR LOOP CODE.
}
delete record. in if condication
document.ff.chk.checked=false;
Hey Viral,
Great work, I’m wondering if it applies a unique field id to each new field row created as im trying to find a new solution for a form i have that submits to a database and my current way seems to stop at 9 entries for some reason, any help or advice is greatly appreciated.
Hi Viral,
Your code helped me a lot. I’m creating dynamic rows in a table with 4 different columns namely : Description, Name, Size, Option. The code is shown below
<form name=”myform” action=” ” method=”POST”>
No.
D
Field Description
Field Name
Field Type
Size
Option
var TABLE_NAME = ‘myTable’;
var ROW_BASE = 0;
var hasLoaded = false;
var flag = false;
window.onload=fillInRows;
function fillInRows()
{
hasLoaded = true;
}
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five, six, seven)
{
this.one = one;
this.two = two;
this.three = three;
this.four = four;
this.five = five;
this.six = six;
this.seven = seven;
}
/*
* addRowToTable
* Inserts at row ‘num’, or appends to the end if no arguments are passed in. Don’t pass in empty strings.
*/
function addRowToTable(num)
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// requires classes named classy0 and classy1
row.className = ‘classy’ + (iteration % 2);
//This whole section can be configured
//left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
//Right cell
var cellRight1 = row.insertCell(1);
var el1 = document.createElement(‘input’);
el1.setAttribute(‘type’, ‘checkbox’);
el1.name = ‘d’ + iteration;
el1.id = ‘d’ + iteration;
cellRight1.appendChild(el1);
var cellRight2 = row.insertCell(2);
var el2 = document.createElement(‘input’);
el2.setAttribute(‘type’, ‘text’);
el2.setAttribute(‘name’, ‘fd’ + iteration);
el2.setAttribute(‘size’, ’25′);
cellRight2.appendChild(el2);
var cellRight3 = row.insertCell(3);
var el3 = document.createElement(‘input’);
el3.type = ‘text’;
el3.name = ‘fn’ + iteration;
el3.id = ‘fn’ + iteration;
el3.size = ’25′;
cellRight3.appendChild(el3);
var cellRight4 = row.insertCell(4);
var el4 = document.createElement(‘select’);
el4.name = ‘ft’ + iteration;
el4.id = ‘ft’ + iteration;
el4.options[0] = new Option(‘Text’);
el4.options[1] = new Option(‘Radio’);
el4.options[2] = new Option(‘Textarea’);
el4.options[3] = new Option(‘Checkbox’);
el4.options[4] = new Option(‘Button’);
el4.options[5] = new Option(‘Drop-downList’)
cellRight4.appendChild(el4);
var cellRight5 = row.insertCell(5);
var el5 = document.createElement(‘input’);
el5.type = ‘text’;
el5.name = ‘sz’ + iteration;
el5.id = ‘sz’ + iteration;
el5.size = ’5′;
cellRight5.appendChild(el5);
var cellRight6 = row.insertCell(6);
var el6 = document.createElement(‘input’);
el6.type = ‘text’;
el6.name = ‘op’ + iteration;
el6.id = ‘op’ + iteration;
el6.size = ’5′;
cellRight6.appendChild(el6);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode,el2, el1, el3, el4, el5, el6);
}
rowCount();
}
function rowCount()
{
var oRows = document.getElementById(‘myTable’).getElementsByTagName(‘tr’);
var iRowCount = oRows.length;
iRowCount = iRowCount – 1;
//alert(‘Your table has ‘ + iRowCount + ‘ rows.’);
}
// this entire function is affected by myRowObject settings
// If there isn’t a checkbox in your row, then this function can’t be used.
function reorderRows(tbl, startingIndex)
{
if (hasLoaded) {
if (tbl.tBodies[0].rows[startingIndex]) {
var count = startingIndex + ROW_BASE;
//alert(‘:)’ + startingIndex + ‘.’);
//alert(tbl.tBodies[0].rows.length + ‘.’);
//var max_rows=tbl.tBodies[0].rows.length;
for (var i=startingIndex; i<=tbl.tBodies[0].rows.length; i++) {
// next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
//next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count; // input text
//requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = ‘classy’ + (count % 2);
count++;
}
}
}
}
function deleteRows(rowObjArray)
{
if (hasLoaded) {
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}
}
}
function deleteChecked()
{
if (hasLoaded) {
var checkedObjArray = new Array();
var cCount = 0;
var tbl = document.getElementById(TABLE_NAME);
for (var i=0; i 0) {
deleteRows(checkedObjArray);
rowCount();
reorderRows(tbl,1);
}
}
}
My question is how to retain the table and the elements in it even after I click submit button (as the page gets refreshed).Please help it is urgent. Also some code might be helpful.
Thanks,
SHRI
@craig
Please check your code of persisting records in database. There must be some bug in that only.
@Shri
I assume you have written your backend code in PHP. While submitting the records to script to persist it, you can save these in an array and put the array in request. When the page is again loaded, you can iterate through this array and create table based on the entries.
Hi Viral,
Your code is very helpful ! I wanted to ask you how I can get values from text boxes in PHP
(how to pass these values form java script to php) ?
Thanks a lot !
Hi Viral, thank you for your tutorial!
But i have a question, do you know if it is possible to insert a row in a table inside another table?
If it is possible, how can i do this? Thank You!
Viral -
This code has been extremely helpful. I’m trying to modify it so that when I add a new row, it will update the element name (e.g., the first line of the table gets stored in a form array called line1[], the secon row goes to line2[]).
I’m using the newcell.childNodes[0].setAttribute(“name”,”line”+rowCount+”[]“); to set the name.
FOr the checkbox and the text element, it updates the name to “line#” where # is the row numner. However, for the select box, it doesn’t seem to do this.
My back end test code is a simpl PHP script that iterates throw the lines and prints out the array of values. All of the values of the select box end up in the line1 array.. ANy ideas??
Modified code:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
document.testForm.totalRows.value=totRows;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
newcell.childNodes[0].name=”line”+rowCount+”[]“;
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
And here’s the output:
Total Rows:3
Line: 1
Array ( [0] => 111 [1] => in [2] => de [3] => fr )
Line: 2
Array ( [0] => 222 )
Line: 3
Array ( [0] => 333 )
Any help would be appreciated!
Nice code, thanks it helped
Hai….How can I have a script program is applied in the form of PHP and MySQL?
How can we incorporate DynaActionForm with this?
Thanks a lot for the code..
@ocef: I have updated the tutorial and added details for fetching these values in PHP.
@850t: You can use normal ActionForm in Struts to get these dynamically row values. You can have String Array of attributes (String [] countries) in your ActionForm and the values will be filled by ActionServlet.
@Prashanth: You welcome :)
Hi Viral,
That is an amazing piece of code. Gr8 work done. I just thought of writing to you as I have a doubt. It would be great if you could advice me as to what to do or any help.
I am able to add the rows and delete it. However how do i validate the dynamically created rows.
What I did was i used the text field name to be validate. However if the number of rows are 5 and if the row one has a value, and other rows empty, it doesnt validate.
So the doubt is how do i validate all the dynamically createdfields.
I would appreciate u r help.
realy great I have added it in my digg
But how to validate that user must have to enter all data in the first example.
Hi Viral,
Thanks a lot for this code. its very useful.
I have little different requirement. i have four rows in my table and when user click on Add button. table should be extended by these four rows. at one time i want to copy four rows and append at the end of table.
is that possible? if yes could you please share the code with me?
And also i want to know if there is any way to preserve the attributes of the copied rows. New created rows should have same attributes (class, align, style) which was there for the existing rows. Any help regarding this will be really helpful. And you can ignore my first request. i am able to achieve it.
nice post
reallu nice post…
Hey Hello,
Thank u very much, this is very nice article.. keep sending this kind of gud articles :):):):)
Hey Viral nice code it really helped but der is one problem…
when i try to alert (newcell.childNodes[0].type) this in case of it says undefined…
actually i tried giving name newcell.childNodes[0].name = “text”+cnt;
it worked for text and checkbox but for select-one it says undefined…. and i was’nt able to name my any solution for this….???
Please mail me da solution if possible…. @ hardikjobalia@gmail.com…..
thnx a ton…
Dear your work is good can u help me out if I plan to generate test box on tab key press event .. no issue there will be button for submit all data … if u can that willl be great …………. wating for replay
regards
Alankar
Hey Viral,
Seriously nice work man.
But I have been stuck @ one place and I am hoping that you can help me out.
The place I’m stuck @ is when passing the array to the next page.
My coding is as follows.
and the addrow button has the exact coding of yours. just the name has been changed.
I have tried the two following methods to display the debit[] array in the next page.
$txtbox = $_POST['debit'];
while (list($a, $b) = each($txtbox)) {
echo “Key: $a; Value: $b\n”;
}
foreach ($txtbox as $key => $value) {
echo “Key: $key; Value: $value\n”;
}
the problem is both the methods will display only the value @ arrayname[0] .
the first index is only being displayed.
can you please help me out.
Viral, Nice work.
Can you please tell me how can I add a Click event to the dynamically added control in the new row(ex: checkbox/button onclick or dropdown on change) ? Thanks in advance.
Hi Taraka, Thanks for the comment.
I think it is easy to attach an event with any of the dynamic component. You just have to assign a handler function to ‘onclick’ event handle. For example for newly created button, we add event as follow:
var element1 = document.createElement(“input”);
element1.type = “checkbox”;
element1.onclick = functionHandler;
function functionHandler() {
…
}
Great… It’s good..
Thnaks
Thnaks
Thanks for your great work. This saved a lot of time and works really well. I do have a question about how to get the “Add Row” to function as expected if I have a header row. I know one of the “0″ need to be different but not sure which one. Any help would be appreciated. Thanks.
@cmorr, Just try to add Header row in your table and that should work. Check one of the above example. I have added the header row and it is working fine.
If we populate the dropdown with values from the database and are using EL ,jstl tags along with form:select and spring:bind tags how do we add multiple rows of dropdown lists dynamically on clicking the add row button with the values populated using javascript.
Tanx viral ur article helped me a lot….
Great man great,,,thanks
Hi
Great article
Thanx
hi Viral,
I find nice in your article that exactly help my need, but I have problem on how to validate textbox if it is empty?
Please Help…Thanks in advance.
hi viral,
Ive got no idea on how to save the inputs to the database in asp c#.
please help….
great work, how do i get the value of these elements in table from code behind.i’m using ur code in vb.net 2003.
Great work.
@RK, Thanks….
hai Viral Patel…. thanks for the code, very easy to understand…. i got 2 question…
1 – how if u don’t want to use checkbox, only use Delete Row button ?
2 – how can i add to database in below PHP code? coz if i use below code to insert 3 data, only 1st data will insert .
————————————————————————————–
$date4=date(‘Y-m-d’,strtotime($_POST['Reg_ReceiptDt']));
$Payment_Mode = $_POST['Payment_Mode'];
$No_DocPayment = $_POST['No_DocPayment'];
$Amount = $_POST['Amount'];
foreach($No_DocPayment as $a => $b)
$insertSQL = sprintf(“INSERT INTO LTG_Payment (IC_NO, Reg_ReciptNo, Reg_ReciptDt, Payment_Mode, Amount, No_DocPayment) VALUES (%s, %s, %s, %s, %s, %s)”,
GetSQLValueString($_POST['IC_NO'], “text”),
GetSQLValueString($_POST['Reg_ReceiptNo'], “text”),
GetSQLValueString($date4, “date”),
GetSQLValueString($Payment_Mode[$a], “text”),
GetSQLValueString($Amount[$a], “double”),
GetSQLValueString($No_DocPayment[$a], “text”));
mysql_select_db($database_conn, $conn);
$Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
——————————————————————————————————–
thanks for your help !!!
Hi VP,
Unfortunately copying rows with columns doesn’t work on Firefox. On IE, the element is called “select-one”, but on Firefox it is undefined! I added a “case” to catch undefined & set selectedIndex, but it didn’t work.
Any suggestions?
Scott. :)
Ah! Just needed to ignore some whitespace nodes. I achieved this by applying the switch statement to ALL the child nodes:
for (var j = 0; j < newcell.childNodes.length; j++)
{
switch (newcell.childNodes[j].type) {
case "text":
…
}
Scott. :)
hi viral,
thanx for the tutorial.
i have been implementing this for my applications. but now i have some problem.
1- i want to add two or more check boxes in a row.( for several purposes otherthan deleting row), but it does not work.
2- for adding a table inside a row and then adding multiple rowes is not working
please help if you are free today. i need it urgently. thanx for your help.
hi viral,
here i am adding my requirement
1
and if possible add comments inthe javascript part. sothat we can modify the code according to ours. it will be handy also.
ITs really great ! . Its helpful for me . I want to know how to delete a entire a row at a strech?
I am having the same problem as Dileep- only the first index is being displayed.
Hey Viral,
Seriously nice work man.
But I have been stuck @ one place and I am hoping that you can help me out.
The place I’m stuck @ is when passing the array to the next page.
My coding is as follows.
and the addrow button has the exact coding of yours. just the name has been changed.
I have tried the two following methods to display the debit[] array in the next page.
$txtbox = $_POST['debit'];
while (list($a, $b) = each($txtbox)) {
echo “Key: $a; Value: $b\n”;
}
foreach ($txtbox as $key => $value) {
echo “Key: $key; Value: $value\n”;
}
the problem is both the methods will display only the value @ arrayname[0] . the first index is only being displayed. can you please help me out.
I was using this method and ran into a debugging issue while deep into some code.
I found the fix so, so here a bit of info that might help someone out who runs into this problem…
Rather that receiving full arrays of data, I would only get the first item, even though the javascript created the form properly. I even did an alert() test to give the input object name, and it was copying over properly, so I was a bit perplexed as to why I had a problem getting values out of it.
It turns out the problem has to do with nesting tables. I had the form spanning across multiple tables (for visual formatting), and it broke the ability to retrieve multiple values for the form. I had a little trick I liked to use, putting the tag between a and tag to suppress a false newline (probably deprecated anyways) and I think that this (aside from being in bad form) caused a DOM nesting problem.
I was able to get around it by moving the and tags outside the outermost table and all was well. I was still able to use multiple tables inside the Form, including the dynamic auto-resizing one, and all is well now. Multiple values still pass to arrays in my PHP script.
By the way, with an unlimited possible number rows in the form, I imagine a person could overflow the POST method. Does anyone know what the maximum amount of data that a request can handle is?
Brian
brian,
Please share more details how you solved the table problem, where only first row is displayed.
Articles posted are very helpfull and gr8…thanks a lot for all
Viral, Great job!!!
If anyone has a similar problem of multiple tables and only first row being read. Please share the solution. It would be a great help. Looking forward.
Brian your solution to the first index display is not clear. I have the same issue. Anyone in the forum has a categorical answer to this. I tried debugging it but no good.
Dileep and Nathan had the same issue too. Were you able to resolve?
James.
“Only first row being displayed….”
I discovered that this issue is with firefox only. The code works well in IE.
If anyone has a work around for FF please share.
hi viral;
am developing a program in javascript it actually gives total as its output .
i used above mentioned code to generate rows automatically. Now the actual thing:
when i started developing this program i used addAll() function to add the amounts that are present in the first table [and the thing is rows were created manually].
it was working fine.
but after i have started generating rows dynamically the addAll() function is not working. can u help me out please?
code is given below:
function addAll(){
var frm = document.f;
var total = 0;
for(var k=0;k<frm.num.length;k++)
{
total+=parseInt(frm.num[k].value);
}
frm.tot.value=total;
}
function addAllFinal(){
a = Number(document.f.txttotal.value);
b = Number(document.f.txtservicetax.value);
c = Number(document.f.txtedutax.value);
d = Number(document.f.txthighedutax.value);
e = Number(document.f.txtoctroi.value);
f=a+b+c+d+e;
document.f.txtgrandtotal.value = f;
}
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";
element2.size = "50";
element2.maxlength = "50";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.size = "5";
element3.maxlength = "5";
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.size = "5";
element4.maxlength = "5";
cell5.appendChild(element4);
var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.value = "00.00";
element5.onblur = "if(!is NAN(this.value)) this.value = '00.00'";
element5.onchange = "addAll()";
cell6.appendChild(element5);
}
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);
}
}
Your Order No.
dated
.
Sr.No.
Description
quantity
Rate
Amount
1
The thing is that my next calculation is working fine but the first table is not.
please help me out.
Hi,
I seriously find this article specially useful for me and is implementing your codes in my application now.
But recently I am facing a problem using your above codes with dojo text boxes. I am able to add new rows with the text boxes in it but however all the dojo properties in the text boxes of the first roll is not being copied to the next cell.
I have a date text box, text area, currency text box and select filter in the respective cells of a table.
Not sure if you are familiar with dojo but please do advise, thank you.
Hi Viral,
This is very nice. But want this to be done using select tag. My requirement is as below.
1. I want to add/delete date values(MM-DD-YYYY)
2. As I add a new date, the list should expand and as I delete date the list should reduce.
3. Right now I can do this. But I want these(dynamically) added values to retain even after submit.
4. how can I do load/store values in select box using web server. I want use entered dates to store in to a data base and then to load them to web page whenever web page is accessed.
Thanks in advance.
hello.. I would like to ask something, I am using something similar with these dynamic forms and I am currently having a problem using a back button.
Ok here’s the situation,
I have a page which contains the dynamic form and a submit button below that page.
When you hit the submit button you will be redirected to a confirmation page which all elements are set to disabled mode (not editable), on the bottom of this page I have a back and confirm button.
When the user hit the “BACK” button, it will be redirected to the previous page, the problem is it doesn’t remember other added rows, it only shows the content of a single row which is declared in the code.
help please.. :)
I used history.go(-1) function.
I will post the solution if ever I solved the problem.
Guys help me please.. :)
Thanks in advance. :)
Hi Batobalani, Did you solve the problem? I have the same requirement.
Best Regards
Hi Viral,
Thanks for giving this code which I was looking for. But I am having another requirement. I am also including a textarea in the form. In the textarea, I am doing a maximum char validation and hence calling a function “onkeypress=”maxLim()” from the textarea. Now I want to call this function from all the newly added textareas in the new rows. So Where and how should I express this function in the addRow?
Appreciate your reply.
Thanks a lot for the tutorial :)
Hi Ratnadeep,
You can use setAttribute() method on newly created textarea to set onkeypress property to maxLim() method. For example:
var txtarea = document.createElement("textarea"); txtarea.setAttribute("onkeypress", "maxLim()");Hope this will work.
dynamic text boxes genareted properly but , value not echo,
and my big problem is ,
how to submit these values in database by inset query.
thanks a lot for this article
i was looking 4 sm thing lyk this only for my ui..
I have a table with one row
each row has two columns
column 1 contains one hidden variable and one checkbox
column 2 contains a texbox.
I have used the similar code as above. However, when the delete row method is invoked, it states undefined for the checkbox, Also it is unable to locate the checked property.
In my case the cell0 child node 1 contains the checkbox
how to do griedview in php which easily done in asp.net i know in asp.net but that thing hw done in php please help me like edit and save in gried or table
Hey you code is great.
But a need limit the rows to 5, ¿how do this?
I try adding if (rowCount >= 5) break;
But a probles is when delete one row and renew adding
please helpme.
Thanks.
Hi Viral,
The article is really very helpful. The one thing that I am facing a problem with is that I am adding a text box with a browse button i.e type “file” dynamically and I want to associate a onChange event with that. But the event is called when the text is placed on the html file , even before the value of text changes.
var element2 = document.createElement(“input”);
element2.name = “data1″
element2.id = “data1″
element2.type = “file”;
element2.onChange = validate();
The validate function gets called as the text is placed on the html form and not when the value of the text box changes ..
Please help!!!
It is really urgent.
Regards
Richa
Plz give me the code specified above in php..
Any on plz give me the php format…
hi viral please help regardin this BUG , deletrow () function with works only in IE but not in Mozilla Fire fox please give me the solution
hi viral the genius,
im having some sort of problems. the code above is very very good and very easy to understand. now, please help with my project, i want to retain the values that i have encoded in the table everytime i run the program. where can i save those info. and how can i edit the info and still rretain the vales. please help me. im begging you. i need to pass the project on march 24, 2010 and im still stuck with your code. i dont know what to do. im a beginner. please help me..
i forgot to tell you, i have three tables, the TABLE.jsp, ADD.jsp, and EDIT.jsp. This is what the program should be.
when i click the add button in the TABLE.jsp, it will go to the ADD.jsp window and has 2 input textboxes and when i click save button it will go to the TABLE.jsp and put the values in the table.
It is also the same in the EDIT.jsp. Thank you. PLEASE HELP ME..
Hi Can some one help me how to add the excel sheet copied columns on to my html page using Java script…clearly i will have the same layout (added textboxes on the HTML page to create the excel layout)of the excel sheet on my html page..once user copies some 20 rows and 10 columns frm the excel sheet i need to paste them on the html page textboxes. Please help me…
Viral Thx for the code..
It’s Really Works..
Hi,
First, thanks alot for the code, but there is this issue connected to the “Add/Remove rows from table having Drop Down List”, If I press submit and there is an empty row or something fro which I have a handler , after submit, remaining in the same page means losing the rows I have added before. Cand you give me an advice about this ?
Thanks,
Emil
Hi, great script and great for sharing, working perfefect in IE but not working in FF.
In FF it only displayes or inserts the first row. In FF like this
array ( ‘sID’ => ’7′, ‘x’ => ’41′, ‘y’ => ’10′, ‘txt’ => array ( 0 => ‘_’, ), ‘country’ => array ( 0 => ‘in’, ), )
In IE like this
array ( ‘sID’ => ’7′, ‘txt’ => array ( 0 => ‘_’, 1 => ”, 2 => ”, ), ‘country’ => array ( 0 => ‘in’, 1 => ‘in’, 2 => ‘in’, ), ‘x’ => ’16′, ‘y’ => ’16′, )
Any ideea on this???
Hi Viral,
I am developing online shopping cart. In that I have used your java script to add more rows on requirement. I am facing problem. The Problem is that by using your script i am able to add more rows dynamically, but i want to insert the value of fields in the database using PHP. can you please help with the script to insert data in the database.
Hi Viral,
I have problem in setting CssClass.
Code i used is working fine Mozilla, but not in IE.
var el = document.createElement(‘input’);
el.setAttribute(‘class’, ‘bstextbox’);
Can you please help me in solving this issue.
good demo
can you use this method in symfony project to add embed form dynamically ??
Anyone else have the problem where the new dynamic rows appear on the page, but when you “view source” they aren’t in the HTML, thus don’t get sent through to the action handler when you submit the form?
I’m doing:
foreach ($_POST as $var => $value)
{
echo “var = “.$var.”, value = “.$value.print_r($value,true).”";
}
But I can only see data from the FIRST ROW, not from any of the dynamic rows.
What’s the secret? I’m using FireFox if that matters.
Figured out the secret, in the Javascript code the new cell elements must have NAMES.
Example. (notice the del[])
var cell1 = row.insertCell(0);
var element1 = document.createElement(“input”);
element1.type = “checkbox”;
element1.name = “del[]“;
cell1.appendChild(element1);
i have used your code and it works fine ….until i used it in some php manipulations…..
the problem is.. —>when i use this code to place my RETRIEVE data’s in my MYSQL the buttons wont work….please help me.. how to fix this? thanks
He this code rocks!!!!
It really works GRT
Superb code Viral …..helped me alot ….
thanks :)
@smita: you welcome :)
Hii Viral,
Thanks alot for the code…
how about if i input date??
Hi Viral.
Nice code.. I tried it and it is working fine with me..
But I’ve a doubt..
I want the data entered in the textboxes to be saved in the database..
I’ve performed the connection to the database and have also given the insert query..
The difficulty is that I dont know how to put the values in the database..
For eg, INSERT INTO table_name VALUES (‘”+records[i]+”‘);
records[] include the array of data to be entered..
Also, the column names are generated at run time using Metadata..
Could you tell me where am I wrong or what am I missing?
How do i add rows in a asp.net DataGrid control using client side script ?
hi,
i wrote java script add/delete code. its working fine in IE, but when i try on this piece of code on Mozilla, i wont work how to run on different browser, if u have solution give it 2 me
Thanks in Advance
Can this be implemented using asp textbox?
Also do you have sample of asp.net wizard control?
Hi Viral,
I have a requirement that in a jsp, I display some rows of data. There is a dropdown for a number.When i call the onchange() event, i want to display exactly that many rows on my jsp.
Any bright ideas/ code snippets??
Hi Vikram very nice example….
has any one figured out the problem with Firefox only displaying the first row data in DB
Can any one please tell me how can i do javascript validation on dynamically created elements.
Thanks for this its really helpful to me. thanks again
how can i submit i try modify code to
Select
Sr. No.
Value
1
but ajaxPost.php is not show somting how can I mix it
i never coding whit ajax but i need learn more
ajaxPost.php
$b)
// echo “$chkbox[$a] – $txtbox[$a] – $country[$a] “;
?>
How do you read the php script in asp code when submitted
hi
i have a problem with a date picker. i implemented a date picker function using yua code and all th other text boxes are all added dynamically but the date picker is also added but i cannot capture the value selected.i fi select the date, it changes the frist records date. so how do you make the calendar function know it is picking a an array of dates??
great code,u solved my problem
thanks,keep it up
Good afternoon
I’m trying the code but I face problem when I included the header with the menu list (it only add the textbox and the checkbox without the menu list when I click on Add row). Another thing I need to know how to pass the value to another page after adding the new row.
Your cooperation is appreciated
darksky
Hey man thnx for help..
But i am using struts 2 will i be able to get values from bean to action? and
i have a row which has 3 differnt columns of date whe n i run this code i couldnt access the calendar.. hw to get rid of that,,, ny 1 plz help will be highly appriciative as i am stuck ;)
Somebody plz tell me how were u able to invoke Fetchrequest.php with submit button? Setting onclick function don’t seem to work as php is a server side scripting lang.
hi viral,
I am very new to struts and java script,i would like to know the code for
1. The form contains username,password,phonenumand one textbox,where i need to enter the number of phone num i hav.
suppose if i enter 3 in that and press add button then i need to generate 3 phonenumber labels,textboxes and one checkbox.
like chechbox label texbox
[] phone1 [ ]
[] phone2 [ ]
[] phone3 [ ]
how i need to generate this
Your cooperation is appreciated
Hello viral,
If i want to add 5 rows at once.. what modifications do i need to make.? also how to update the row id incase of deleting 1 or more selected rows?
Hello Viral,
I used the code above and it works fine. I have another related problem though that I would greatly appreciate if you assisted.
I have a table with 3 columns and n rows that are populated dynamically from the database. The first two columns have text and the last column has checkboxes. I want to implement a procedure that will access the checkboxes i.e. chkbox = row.cells[2].childNodes[0] and check the checkboxes once the user clicks a button “select all rows” i.e. chkbox.checked = true.
There are no errors thrown but it is still not working…HELP!! :-(
Hi Viral,
The code is very useful. I’m just new here in jsp and I’m trying to research on some tips. Anyway, I just want to ask. What If I added command button on each row then if I click 1 of the added command button, it will show the text in that particular row?
Thanks in advance
What if i want to delete entire column from the table..
Nice work man :)
how can u put the value into the database? it can retrieve only 1st row :( anyone could help on this issue?
thanks in advance
function addRow(){
var tbody = document.getElementById(“mapping_row”).getElementsByTagName(“tbody”)[0];
var w = document.getElementById(‘pals_org_id’).selectedIndex;
var selected_text = document.getElementById(‘pals_org_id’).options[w].text;
for(var i =0; i < document.mainForm.elements.length; i++)
{
var type = document.mainForm.elements[i].type;
if(type=="hidden")
{
if(document.mainForm.elements[i].value == document.getElementById('pals_org_id').value)
{
return;
}
}
}
document.getElementById('mappingMessage').style.display = 'block';
var htmlText = '’+selected_text+ ‘ Login ID ‘;
htmlText = htmlText + ”;
htmlText = htmlText + ”;
var row = document.createElement(“tr”);
var newtd = document.createElement(“td”);
newtd.innerHTML=htmlText;
row.appendChild(newtd);
tbody.appendChild(row);
}
hi viral
how to save this row values in database
How can I edit and update row from grid ? Can anyone have that code in JavaScript . I.e currently we are adding and deleting rows.
Thanks
Vinit
hello viral, how can I put the data in rows to a database? please help i really need it. please please please.
thanks!
Hi
I found a similar code and have adapted it somewhat because I’m actually using it for a navigation bar on a table-based page. Only thing I haven’t worked out how to do is to add a row and specify more stuff for the generated cells. I need to be able to specify stuff like background color, font, font size, etc. i also need the cells to have links in them. it would be easier if i could somehow get it to load a pre-created table row from another page (like an iFrame). i dont know how javascript works, i have had to work out what each bit of the code does so that i could edit it. so far i have the following:
function addRow()
{
var _table = document.getElementById(‘table1′).insertRow(1);
var cell0 = _table.insertCell(0);
var cell1 = _table.insertCell(1);
cell0.innerHTML = ‘New Cell1′;
cell1.innerHTML = ‘New Cell2′;
}
function addRow2()
{
var _table = document.getElementById(‘table1′).insertRow(1);
var cell0 = _table.insertCell(0);
var cell1 = _table.insertCell(1);
cell0.innerHTML = ‘Navi1′;
cell1.innerHTML = ‘Navi2′;
}
function removeRow(rows)
{ var _row = rows.parentElement.parentElement;
document.getElementById(‘table1′).deleteRow(1);
}
thats in the head, and the rest is a table in the body
Row1 cell1
Row1 cell2
sorry the body part didnt show as coding because this site just loaded it as a table (which it is). how do i put code into this page?
<!–this is in the body (it's just a table)
Row1 cell1
Row1 cell2
end of the table–>
here the solution how to inset the multiple value in 1 query :)
below is the declaration of the input text from your inset page.
$rowcount = $_POST['rowcount'];
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
$country = $_POST['country'];
here is limit for your Primary Key (inset Value)
$limit = count($txtbox);
//echo “”.$_POST['rowcount'].”";
for($i=0; $i $b)
{
//echo “$chkbox[$a] – $txtbox – $country[[$a] “;
$query = ” INSERT INTO tablename (—–,——) values (‘”.$txtbox.”‘, ‘”.$country[$a].””)”;
mysql_query($query,$connection);
}
echo “You have succesffully Updated your work experiences “;
do let me know if you all still cannot insert the value :)
I am using Joomla and an extension called RSFormsPro which doies not allow me to add new rows for my fields. Who can help me with getting this to work with RSFormsPro?
Thanks.
Keep writing, its nice.