Dynamically Add or Remove Rows in HTML Table using JQuery

Add or Remove Rows in HTML Table using JQuery

In this example, We will show you about, How to Dynamically Add or Remove Rows in HTML Table using JQuery.

Script

var count = 1;
		
		function addRow() {
		
			var data = '<tr class="row'+count+'"><td><input type="text" name="itemName" id="itemName'+count+'" /></td><td><input type="text" name="itemDescription" id="itemDescription'+count+'" /></td><td><input type="button" value="Add" onclick="addRow();" /> <input type="button" value="Remove" onclick="removeRow(this);" /></td></tr>';
			
			$('#itemTable').append(data);
			
			count++;
		}
		
		function removeRow(obj) {
		
			$(obj).closest('tr').remove();
		}

Complete Example

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add or Remove Rows in HTML Table using JQuery</title>
</head>
<body>
	
	<h1>Add or Remove Rows in HTML Table using JQuery</h1>
	
	<div>
		<table cellpadding="5" cellspacing="5" border="1" id="itemTable">
			<tr>
				<th>Item Name</th>
				<th>Item Description</th>
				<th>Action</th>
			</tr>
			<tr class="row0">
				<td><input type="text" name="itemName" id="itemName0" /></td>
				<td><input type="text" name="itemDescription" id="itemDescription0" /></td>
				<td>
					<input type="button" value="Add" onclick="addRow();" />
					<input type="button" value="Remove" onclick="removeRow(this);" />
				</td>
			</tr> 
		</table>
	</div>
	
	<script>
	
		var count = 1;
		
		function addRow() {
		
			var data = '<tr class="row'+count+'"><td><input type="text" name="itemName" id="itemName'+count+'" /></td><td><input type="text" name="itemDescription" id="itemDescription'+count+'" /></td><td><input type="button" value="Add" onclick="addRow();" /> <input type="button" value="Remove" onclick="removeRow(this);" /></td></tr>';
			
			$('#itemTable').append(data);
			
			count++;
		}
		
		function removeRow(obj) {
		
			$(obj).closest('tr').remove();
		}
		
	</script>
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
	
</body>
</html>

Output

Add or Remove Rows in HTML Table using JQuery