Dynamically Add/Delete HTML Table Rows Using Javascript

In this article, you will learn how to create a simple user interface where user can add or delete multiple table rows in a form dynamically using javascript.

Sometimes, there may be requirement to the user to add multiple repeated row's fields in a form. We cannot assume, how much fields we should provide on the webpage. Like, we need to provide some employees details. There is no any surety of how many employee details, may be later we have to delete some. In such case, we can add or remove the entire row with there input fields dynamically using javascript. We have provided two buttons, the first button to add new rows to the table and the second to remove rows.

Dynamically Add/Delete HTML Table Rows Using Javascript

As we know, Javascript is a dynamic language. It means it can control, access and manipulate the HTML elements dynamically on the client side. We can easily add and remove HTML elements in a web page using Javascript. In this article, we will provide you a simple way to add or remove HTML table row with there fields dynamically.

The below code has an HTML form and two javascript functions addRows() and deleteRows() to add and delete the table rows respectively.

<html>
<head>
<title>Onclick increase Table Rows</title>
<script type="text/javascript">
function addRows(){ 
	var table = document.getElementById('emptbl');
	var rowCount = table.rows.length;
	var cellCount = table.rows[0].cells.length; 
	var row = table.insertRow(rowCount);
	for(var i =0; i <= cellCount; i++){
		var cell = 'cell'+i;
		cell = row.insertCell(i);
		var copycel = document.getElementById('col'+i).innerHTML;
		cell.innerHTML=copycel;
		if(i == 3){ 
			var radioinput = document.getElementById('col3').getElementsByTagName('input'); 
			for(var j = 0; j <= radioinput.length; j++) { 
				if(radioinput[j].type == 'radio') { 
					var rownum = rowCount;
					radioinput[j].name = 'gender['+rownum+']';
				}
			}
		}
	}
}
function deleteRows(){
	var table = document.getElementById('emptbl');
	var rowCount = table.rows.length;
	if(rowCount > '2'){
		var row = table.deleteRow(rowCount-1);
		rowCount--;
	}
	else{
		alert('There should be atleast one row');
	}
}
</script>
</head>
<body>
<form action="#" method="post">    
	<table id="emptbl">
		<tr>
			<th>Employee Name</th>
			<th>Phone</th>
			<th>Department</th> 
			<th>Gender</th> 
		</tr> 
		<tr> 
			<td id="col0"><input type="text" name="empname[]" value="" /></td> 
			<td id="col1"><input type="text" name="phone[]" value="" /></td> 
			<td id="col2"> 
			<select name="department[]" id="dept"> 
			<option value="0">Select Department</option> 
			<option value="1">Sales</option>
			<option value="2">IT</option>
			<option value="3">Warehouse</option>
			</select> 
		        </td> 
		        <td id="col3"> 
			<input type="radio" name="gender[0]" value="male" />Male 
			<input type="radio" name="gender[1]" value="female" />Female 
		        </td> 
		</tr>  
	</table> 
	<table> 
		<tr> 
			<td><input type="button" value="Add Row" onclick="addRows()" /></td> 
			<td><input type="button" value="Delete Row" onclick="deleteRows()" /></td> 
			<td><input type="submit" value="Submit" /></td> 
		</tr>  
	</table> 
 </form> 
</body> 
</html>

In the above code, we have taken a form element with three buttons to Add Row, Delete Row and Submit form data. Within the form element, we have taken a table to display the form input data. To perform dynamic operations on the table using Javascript, we have given an id 'emptbl' to table.



Steps: Javascript add rows to table dynamically

These are the step by step code explanation on how a new row is dynamically created when a user click on the 'Add Row' button.

addRows() - Within the head section, we have created a Javascript function name addRows() that is responsible to add new table row with input fields. For this, first we got the table element with table id and stored in a javascript variable table.

var table = document.getElementById('emptbl');

Next, we stored the number of <tr> element using Javascript property rows.length in a variable rowCount and rows[0].cells.length property returns number of <td> elements of first row.

var rowCount = table.rows.length;
var cellCount = table.rows[0].cells.length;

Next, we have created an empty row using Javascript property insertRow().

var row = table.insertRow(rowCount);

Next, we have dynamically generated the cells within the empty row using for loop and taken the innerHTML of the old cell with cell index and paste in new one.

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

}


Steps: Javascript delete rows of table dynamically

These are the step by step code explanation on how an existing row is dynamically deleted when user click on the 'Delete Row' button.

deleteRows() - Within the head section after addRows() function, we have created another Javascript function name deleteRows() that is responsible to delete existing table row with input fields. For this, first we got the table element with table id and stored in a variable table.

Next, we stored the number of <tr> element using property rows.length in a variable rowCount.

var rowCount = table.rows.length;

Next, using the IF Else statement, we have checked, weather number of table rows is greater than one or not.

if(rowCount > '2'){

}

If it is TRUE, then it deletes one row with Javascript property deleteRow() and decrement the number of rows by one.

var row = table.deleteRow(rowCount-1);
rowCount--;

We hope this code helps someone. You can implement this easily with minor edits. During implementation, please take care of table id and columns id.

Screenshot of Add/Delete Table Rows

 



Related Articles

JavaScript display PDF in the browser using Ajax call
How to Retrieve Emails from Gmail using PHP IMAP
Retrieve Data From Database Without Page refresh using AJAX, PHP and Javascript
How to print specific part of a web page in javascript
How to store Emoji character in MySQL using PHP
How to display PDF file in PHP from database
jQuery loop over JSON result after AJAX Success
Dynamically Add/Delete HTML Table Rows Using Javascript
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
How to add google reCAPTCHA v2 in registration form using PHP
Complete HTML Form Validation in PHP




Read more articles


General Knowledge



Learn Popular Language