etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Dynamically Add/Delete HTML Table Rows Using JavaScript

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





Sometimes, there may be a requirement for the user to assign data to the <td> of a table dynamically using JavaScript for multiple rows. We cannot assume how many fields we should provide on the webpage. Like, we need to provide some employee details. There is no way to know for sure how many employee details there are. Maybe later we'll have to delete some. Let's discuss how columns, rows, and cells will be dynamically created or removed in the HTML table using JavaScript.

In this post, we will provide two buttons, the first to add new rows to the table and the second to remove rows. The code will add or remove the entire row along with their input fields dynamically.

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. Using JavaScript, we can easily add and remove HTML elements from a web page. In this article, we will provide you with a simple way to add or remove HTML table rows and their fields dynamically.

The below code has an HTML form and two JavaScript functions. To add and delete table rows, use addRows() and deleteRows(), 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 created a form element with three buttons to Add Row, Delete Row, and Submit form data. Within the form element, we have created a table to display the form input data. To perform dynamic operations on the table using JavaScript, we have given an id 'emptbl' to the table.





Steps: JavaScript adds rows to table dynamically

These are the step-by-step code explanations of how a new row is dynamically created when a user clicks on the 'Add Row' button.

addRows() - Within the head section, we have created a JavaScript function named addRows() that is responsible for adding a new table row with input fields. For this, first we got the table element with the table id and stored it in a JavaScript variable table.

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

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

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

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

var row = table.insertRow(rowCount);

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

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

}




Steps: JavaScript deletes rows of the table dynamically

These are the step-by-step code explanations of how an existing row is dynamically deleted when a user clicks the 'Delete Row' button.

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

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

var rowCount = table.rows.length;

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

if(rowCount > '2'){

}

If it is TRUE, then it deletes one row with the JavaScript property deleteRow() and decrements 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

Find index of element in array JavaScript
JavaScript Array Slice
Download and open PDF file using Ajax
JavaScript window location
How to reverse a number in JavaScript
How to reverse string in JavaScript
PHP script to read email inbox
How to retrieve data from database without refreshing page
Print specific part of webpage
Store Emoji character in MySQL using PHP
PHP Display PDF file from Database
jQuery ajax loop through data
Dynamically add/remove rows in html table using jQuery
Submit form without page refresh using JavaScript
PHP Form Validation Tutorial
Google reCAPTCHA v3 PHP example
Select/deselect all checkboxes using JavaScript
JavaScript speech recognition example
Image popup on page load using HTML and jQuery
jQuery File upload progress bar with file size validation
Simple calculator using JavaScript
Palindrome number in JavaScript
Remove duplicates from array JavaScript
Scientific calculator JavaScript




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.