Dynamically Add/Remove rows in HTML table using JavaScript

[ad name=”AD_INBETWEEN_POST”] 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";
			element1.name="chkbox[]";
			cell1.appendChild(element1);

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

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


		}

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

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


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

	</SCRIPT>
</HEAD>
<BODY>

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

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

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

</BODY>
</HTML>

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

Check the online demo.

Online Demo


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 />";

?>

If you read this far, you should follow me on twitter here.

Get our Articles via Email. Enter your email address.

You may also like...

496 Comments

  1. ketan says:

    need help in making form elements unique for Ex

    —->Array[0]–>india
    —–>Array[1]–>india

  2. Bill Evans says:

    Is there a way to determine if one of the rows has multiple column spans in the first td. If it does I need to change the cell index.

  3. thejesh says:

    very useful code…

  4. nad says:

    hi,
    can you put the header of the table also?

    Add row Delete
    ———————————————–
    S.# Name Age City Country
    ———————————————–
    1 patel 22 dehli india

    ————————————————

    thanks

  5. Ricardo says:

    hi!..
    how to add a multi row into the database?

  6. rey says:

    how to save in the database?

  7. Madhu says:

    Dear Viral Patel,

    Thanks for your coding. And its works in that way. But i wants to control the # of fields to be created like to say i wants just only 5 text boxes, 5 check boxes and 5 drop down list( basically i can possible to create 5 only and then, nothing much even though i press add items more than that).

    Is that possible?

    Thanks.

  8. Huda says:

    What does this line mean?

    $a =--> $b

    Sorry new to php

  9. Ryan says:

    Can you help me please, I’m using bootstrap and I am getting frustrated.

  10. Daniel says:

    Great!!!!

  11. Sumi says:

    Hi Patel,
    Thanks for sharing the code.Using your code I am trying to submit the form.jsp to another insert.jsp. Can you please help me out with code.
    1) How I can fetch the data of dynamically created text boxes from form.jsp to insert.jsp.
    2) Want to get name of employee from database by onBlur function sendInfo() on ttm_id textbox

    My code is as follow in form.jsp (javascript)
    function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    alert(“rowCount = ” + rowCount);

    var cell1 = row.insertCell(0);
    cell1.style.borderColor = “transparent”;
    var element1 = document.createElement(“input”);
    element1.type = “checkbox”;
    element1.name=”chkbox”;
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    cell2.setAttribute(“align”,”center”);
    cell2.style.borderColor = “transparent”;
    var element2 = document.createElement(“input”);
    element2.type = “text”;
    element2.disabled = “true”;
    element2.style.backgroundColor=”transparent”;
    element2.name = “ttm_slno[[]”;
    element2.size = “5”;
    element2.style.borderColor = “transparent”;
    element2.style.textAlign = “center”;
    element2.value = rowCount + 1;
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    cell3.setAttribute(“align”,”center”);
    cell3.style.borderColor = “transparent”;
    var element3 = document.createElement(“input”);
    element3.type = “text”;
    element3.name = “ttm_id[]”;
    element3.size = “10”;
    element3.maxLength = “10”;
    element3.style.textAlign = “center”;
    //element3.onBlur = sendInfo();
    cell3.appendChild(element3);

    var cell4 = row.insertCell(3);
    cell4.setAttribute(“align”,”center”);
    cell4.style.borderColor = “transparent”;
    var element4 = document.createElement(“input”);
    element4.type = “text”;
    element4.name = “ttm_name[]”;
    element4.size = “25”;
    element4.maxLength = “25”;
    element4.style.textTransform = “uppercase”;
    cell4.appendChild(element4);
    }

    insert.jsp

    <%
    if(ttm_id != null) {
    for(int i=0;i

    <input type="text" name="ttm_slno" value= "” size=”5″ readonly=”readonly”
    style=”border-color:transparent; text-align:center;”/>
    <input type="text" size="7" name="ttm_id" value="” readonly=”readonly”
    style=”border-color:transparent; text-align:center;”/>
    <input type="text" size="25" name="ttm_name" value="” readonly=”readonly”
    style=”text-transform: uppercase; border-color:transparent; text-align:center;”/>

  12. Gana says:

    Hello,
    I am very interested in this. Thanks for the tutorial.
    Furthermore, I have some problem with it. I want to make a select (dropdown) using Select2 (styling plugins). However, I got my select2 didn’t work, the 2nd till the last row somehow became un-clickable.
    Then I realise, select2 won’t work for dynamically generated select. Do you have a workaround that works?
    Thanks.

  13. nikitha says:

    how to add or delete row based on data passed from json file

  14. Lawrence says:

    Why I can not set
    It doesn’t enter switch case “select-one”

  15. Thanks for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *