Dynamically Add/Remove rows in HTML table using JavaScript

      

A good web design involves the better user interaction and ability to fetch the data in a better way. For fetching user data, you may have to create a form wherein user can add multiple entries and submit them simultaneously.

Thus for this you will need a way to add or remove fields dynamically into the HTML page. In my previous article, I had discussed about the way one can add dynamic form components into the web page.

In this article we will create a user interface where user can add/delete multiple rows in a form using JavaScript.

First check the user interface.
dynamic-add-delete-row-table-javascript

In this example, we have created a table which will display our html components. On pressing Add Row, a dynamic row will be created and added in the table. And on selecting the checkbox and pressing Delete Row, the row will be removed.

Following is the source.

Code

<HTML>
<HEAD>
	<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
	<SCRIPT language="javascript">
		function addRow(tableID) {

			var table = document.getElementById(tableID);

			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);

			var cell1 = row.insertCell(0);
			var element1 = document.createElement("input");
			element1.type = "checkbox";
			cell1.appendChild(element1);

			var cell2 = row.insertCell(1);
			cell2.innerHTML = rowCount + 1;

			var cell3 = row.insertCell(2);
			var element2 = document.createElement("input");
			element2.type = "text";
			cell3.appendChild(element2);

		}

		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;

			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					table.deleteRow(i);
					rowCount--;
					i--;
				}

			}
			}catch(e) {
				alert(e);
			}
		}

	</SCRIPT>
</HEAD>
<BODY>

	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

	<TABLE id="dataTable" width="350px" border="1">
		<TR>
			<TD><INPUT type="checkbox" name="chk"/></TD>
			<TD> 1 </TD>
			<TD> <INPUT type="text" /> </TD>
		</TR>
	</TABLE>

</BODY>
</HTML>

For adding dynamic row in table, we have used insertRow() method. This method will insert a row at position specified by the index arguement. Also for removing row, we have used deleteRow() method.
Note that for inserting dynamic row, we have to created cells by using row.insertCell() method.

Check the online demo.

Online Demo


Click here.

Add/Remove rows from table having Drop Down List

What if my table has a selectbox or drop down list and I want to implement add/remove row functionality? A lot of people asked me this question (you can check comment section), so I thought to update this article and add one more case. Adding / Removing rows in a table having drop down list.

Following is the code:

<HTML>
<HEAD>
	<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
	<SCRIPT language="javascript">
		function addRow(tableID) {

			var table = document.getElementById(tableID);

			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);

			var colCount = table.rows[0].cells.length;

			for(var i=0; i<colCount; i++) {

				var newcell	= row.insertCell(i);

				newcell.innerHTML = table.rows[0].cells[i].innerHTML;
				//alert(newcell.childNodes);
				switch(newcell.childNodes[0].type) {
					case "text":
							newcell.childNodes[0].value = "";
							break;
					case "checkbox":
							newcell.childNodes[0].checked = false;
							break;
					case "select-one":
							newcell.childNodes[0].selectedIndex = 0;
							break;
				}
			}
		}

		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;

			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					if(rowCount <= 1) {
						alert("Cannot delete all the rows.");
						break;
					}
					table.deleteRow(i);
					rowCount--;
					i--;
				}

			}
			}catch(e) {
				alert(e);
			}
		}

	</SCRIPT>
</HEAD>
<BODY>

	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

	<TABLE id="dataTable" width="350px" border="1">
		<TR>
			<TD><INPUT type="checkbox" name="chk"/></TD>
			<TD><INPUT type="text" name="txt"/></TD>
			<TD>
				<SELECT name="country">
					<OPTION value="in">India</OPTION>
					<OPTION value="de">Germany</OPTION>
					<OPTION value="fr">France</OPTION>
					<OPTION value="us">United States</OPTION>
					<OPTION value="ch">Switzerland</OPTION>
				</SELECT>
			</TD>
		</TR>
	</TABLE>

</BODY>
</HTML>

Check the addRow() method in above code. I have edited this piece of code from our previous example. The addRow() method iterates through all the columns and copy the content of 1st column to new column. This way a new row is created which is exact copy of 1st row. Also the switch{} case in the code make sure that the value are not copied as it is. For example, if you have entered text “abc” in textbox of 1st row and you press Add Row button, the new row will be added and the textbox of this new row will have value “abc”. So to make sure the values are not copied, we have added the switch{} code.

You may want to comment the switch{} code if the copying of the values in newly added row if desired to you.

Online Demo


Click here.

Getting Submitted Form Values in PHP

The main purpose of above code is to take input from user and persist it in database. Hence we may want to submit the above form and fetch its values in PHP to store the data in database.

If you notice we have multiple input textboxes with the same name. So in order to get these values in PHP request parameter, we need to modify our HTML. We need to append [] at the end of name of each input boxes including select box.

Thus our textbox definition:

<INPUT type="text" name="txt">

Will change into:

<INPUT type="text" name="txt[]">

Also the checkbox and select box definition change to:

<INPUT type="checkbox" name="chk[]"/>

<SELECT name="country[]">
	<OPTION value="in">India</OPTION>
	<OPTION value="de">Germany</OPTION>
	<OPTION value="fr">France</OPTION>
	<OPTION value="us">United States</OPTION>
	<OPTION value="ch">Switzerland</OPTION>
</SELECT>

Once we have changed the HTML code, add a submit button at the end of the form and submit this form to Fetchrequest.php

Following will be the code to get the values from request in PHP and displaying them on screen:

<?php
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
$country = $_POST['country'];

foreach($txtbox as $a => $b)
  echo "$chkbox[$a]  -  $txtbox[$a]  -  $country[$a] <br />";

?>

Facebook  Twitter      Stumbleupon  Delicious
  

99 Comments on “Dynamically Add/Remove rows in HTML table using JavaScript”

  • Kris wrote on 17 March, 2009, 20:25

    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

  • Samir wrote on 2 April, 2009, 0:22

    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.

  • Viral Patel wrote on 2 April, 2009, 11:53

    Thank you Samir for valuable comment.

  • erick wrote on 11 April, 2009, 22:21

    how do i display my entry?

  • Viral Patel wrote on 12 April, 2009, 6:52

    Hi Erick,
    I am not sure if I get you, but do you mean to display a cell element?

  • rynn wrote on 18 April, 2009, 12:16

    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

  • akanksha wrote on 15 May, 2009, 2:18

    hey.. superb code!! but how to call function on generated rows, for eg : onblur so on??

  • Kenny wrote on 20 May, 2009, 15:55

    The row id can’t refresh.

  • Jean Fisher wrote on 24 May, 2009, 7:13

    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?

  • Viral Patel wrote on 25 May, 2009, 21:28

    @Jean: You can send me email at viralpatel [dot] net [at] gmail [dot] com.

  • Mihir Naik wrote on 27 May, 2009, 13:40

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

  • Viral Patel wrote on 27 May, 2009, 14:44

    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.

  • Mihir Naik wrote on 28 May, 2009, 9:27

    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 ?

  • Viral Patel wrote on 28 May, 2009, 11:15

    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().

  • Mihir Naik wrote on 28 May, 2009, 16:21

    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 ….

  • Viral Patel wrote on 28 May, 2009, 17:00

    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.

  • dhana wrote on 3 June, 2009, 11:15

    this is a nice article …..keep it up

  • minie wrote on 12 June, 2009, 14:10

    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.

  • Viral Patel wrote on 15 June, 2009, 13:30

    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.

  • Rakesh wrote on 25 June, 2009, 17:28

    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.

  • Raj wrote on 1 July, 2009, 16:45

    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

  • Viral Patel wrote on 1 July, 2009, 18:38

    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.

  • Raj wrote on 2 July, 2009, 12:36

    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?

  • Raj wrote on 2 July, 2009, 12:53

    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

  • Viral Patel wrote on 2 July, 2009, 13:17

    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.

  • Jolog wrote on 5 July, 2009, 11:35

    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 \\&quot;United States\\&quot; all Cities under United Sates must filled the second drop down. Thanks in advance.

  • shesharaj wrote on 5 July, 2009, 18:08

    hi Very nice

    i\\\’m using this code.. but i want one more sol.how to get (Click button)dyamic table row value..

  • Raj wrote on 6 July, 2009, 11:05

    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

  • francis wrote on 13 July, 2009, 23:05

    hey thankyou so much keep the good work

  • Sabiha wrote on 15 July, 2009, 15:15

    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

  • Vilart wrote on 17 July, 2009, 14:24

    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

  • devbrat wrote on 22 July, 2009, 19:48

    hey thanks i have ued your code so it was very use full to me.

  • prabin wrote on 24 July, 2009, 11:59

    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?

  • Raj wrote on 28 July, 2009, 18:07

    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;

  • Craig wrote on 28 July, 2009, 20:52

    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.

  • SHRI wrote on 29 July, 2009, 8:39

    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

  • Viral Patel wrote on 29 July, 2009, 14:15

    @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.

  • Rob wrote on 29 July, 2009, 18:06

    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 !

  • Marcio wrote on 30 July, 2009, 18:16

    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!

  • R. Fischman wrote on 6 August, 2009, 23:01

    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!

  • Ally wrote on 11 August, 2009, 12:23

    Nice code, thanks it helped

  • ocef wrote on 11 August, 2009, 13:16

    Hai….How can I have a script program is applied in the form of PHP and MySQL?

  • 850t wrote on 28 August, 2009, 9:16

    How can we incorporate DynaActionForm with this?

  • Prashanth wrote on 28 August, 2009, 14:09

    Thanks a lot for the code..

  • Viral Patel wrote on 28 August, 2009, 14:37

    @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 :)

  • rohit wrote on 2 September, 2009, 9:50

    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.

  • latest technology wrote on 2 September, 2009, 9:56

    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.

  • Mangat wrote on 2 September, 2009, 12:08

    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?

  • Mangat wrote on 2 September, 2009, 12:55

    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.

  • vats thakur wrote on 4 September, 2009, 23:07

    nice post

  • vats thakur wrote on 4 September, 2009, 23:08

    reallu nice post…

  • Rohit Puranik wrote on 10 September, 2009, 16:17

    Hey Hello,
    Thank u very much, this is very nice article.. keep sending this kind of gud articles :):):):)

  • Hardik wrote on 16 September, 2009, 9:42

    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…

  • alankar jadhav wrote on 24 September, 2009, 5:08

    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

  • Dileep wrote on 28 September, 2009, 6:06

    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.

  • Taraka wrote on 29 October, 2009, 8:25

    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.

  • Viral Patel wrote on 30 October, 2009, 19:01

    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() {

    }

  • Rathin wrote on 5 November, 2009, 15:39

    Great… It’s good..
    Thnaks

  • electroarab wrote on 5 November, 2009, 21:06

    Thnaks

  • cmorr wrote on 9 November, 2009, 19:59

    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.

  • Viral Patel wrote on 10 November, 2009, 16:06

    @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.

  • Gayathri wrote on 17 November, 2009, 0:35

    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.

  • Santosh wrote on 20 November, 2009, 11:18

    Tanx viral ur article helped me a lot….

  • Bijoy george wrote on 24 November, 2009, 17:36

    Great man great,,,thanks

  • Amit Patil wrote on 25 November, 2009, 16:37

    Hi
    Great article
    Thanx

  • nosaj wrote on 30 November, 2009, 14:24

    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.

  • nosaj wrote on 1 December, 2009, 7:04

    hi viral,
    Ive got no idea on how to save the inputs to the database in asp c#.
    please help….

  • test wrote on 2 December, 2009, 16:38

    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.

  • RK wrote on 3 December, 2009, 15:24

    Great work.

  • Viral Patel wrote on 3 December, 2009, 16:05

    @RK, Thanks….

  • 2uk3y wrote on 7 December, 2009, 11:44

    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 !!!

  • Scottie wrote on 15 December, 2009, 6:45

    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. :)

  • Scottie wrote on 16 December, 2009, 5:10

    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. :)

  • sidhartha wrote on 21 December, 2009, 11:23

    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.

  • sidhartha wrote on 21 December, 2009, 12:16

    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.

  • Arun wrote on 22 December, 2009, 16:10

    ITs really great ! . Its helpful for me . I want to know how to delete a entire a row at a strech?

  • Nathan wrote on 29 December, 2009, 23:06

    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.

  • Brian wrote on 30 December, 2009, 2:04

    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

  • ar wrote on 31 December, 2009, 0:15

    brian,

    Please share more details how you solved the table problem, where only first row is displayed.

  • Srinivas Angara wrote on 31 December, 2009, 11:35

    Articles posted are very helpfull and gr8…thanks a lot for all

  • ar wrote on 1 January, 2010, 0:33

    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.

  • james wrote on 3 January, 2010, 1:40

    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.

  • ar wrote on 4 January, 2010, 9:20

    “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.

  • saurabh wrote on 7 January, 2010, 15:47

    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.

  • Mark wrote on 8 January, 2010, 16:10

    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.

  • harishiva wrote on 20 January, 2010, 9:55

    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.

  • Batobalani wrote on 26 January, 2010, 8:58

    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. :)

  • Gerald wrote on 28 January, 2010, 2:25

    Hi Batobalani, Did you solve the problem? I have the same requirement.
    Best Regards

  • Ratnadeep wrote on 31 January, 2010, 9:18

    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.

  • Kittu wrote on 1 February, 2010, 10:41

    Thanks a lot for the tutorial :)

  • Viral Patel wrote on 1 February, 2010, 15:59

    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.

  • rakesh wrote on 5 February, 2010, 15:57

    dynamic text boxes genareted properly but , value not echo,
    and my big problem is ,
    how to submit these values in database by inset query.

  • ashu wrote on 11 February, 2010, 16:43

    thanks a lot for this article
    i was looking 4 sm thing lyk this only for my ui..

  • treasa wrote on 15 February, 2010, 23:59

    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

  • shaily wrote on 21 February, 2010, 23:44

    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

  • PsyCraft wrote on 22 February, 2010, 22:32

    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.

  • richa wrote on 23 February, 2010, 16:46

    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

  • Amar wrote on 24 February, 2010, 15:37

    Plz give me the code specified above in php..

    Any on plz give me the php format…

  • vaibhav wrote on 5 March, 2010, 18:08

    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

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.