Dynamically Add and Delete rows in Html and Javascript
This is a small blog post which will provide
you the simplest approach to dynamically add and delete rows using javascript
and HTML.
Introduction
This small blog post will help you in creating
an HTML page where you can add and delete rows using javascript. In most of the
cases, it is required in the project to add more rows. Let us take an example
common timesheet application or your expense details where the user adds more rows
and it should be dynamic. Also, it is required to delete the unimportant rows
from the table. In this, I blog I will provide you a very basic and the simplest
to achieve it.
Technicalities
The easiest way to achieve the functionality
is to use an Html table and write two javascript functions to add and delete
rows. Sometimes people get confused at the time of requirements and try to use
some external javascript framework. I have seen developers use JQuery to achieve
this functionality. However JQuery is a great framework to achieve many things
by writing less code. But from the view point legacy project, it may not be
required to use JQuery. Let us take an example of financial calculation which is
existing for the last 10 years and it has been developed in JSP with Javascript.
In this case it is not advisable to use external javascript framework as there
is a chance of UI distortion. Let me provide you the java script code for
addition and deletion of rows.
- function addRow(tableID) {
- var table = document.getElementById(tableID);
- var rowCount = table.rows.length;
- var row = table.insertRow(rowCount);
- //Column 1
- var cell1 = row.insertCell(0);
- var element1 = document.createElement("input");
- element1.type = "button";
- var btnName = "button" + (rowCount + 1);
- element1.name = btnName;
- element1.setAttribute('value', 'Delete'); // or element1.value = "button";
- element1.onclick = function() {
- removeRow(btnName);
- }
- cell1.appendChild(element1);
- //Column 2
- var cell2 = row.insertCell(1);
- cell2.innerHTML = rowCount + 1;
- //Column 3
- var cell3 = row.insertCell(2);
- var element3 = document.createElement("input");
- element3.type = "text";
- cell3.appendChild(element3);
- }
- function removeRow(btnName) {
- try {
- var table = document.getElementById('dataTable');
- var rowCount = table.rows.length;
- for (var i = 0; i < rowCount; i++) {
- var row = table.rows[i];
- var rowObj = row.cells[0].childNodes[0];
- if (rowObj.name == btnName) {
- table.deleteRow(i);
- rowCount--;
- }
- }
- } catch (e) {
- alert(e);
- }
- }

Rashmi RansinghPosted Mar 5, 2022, 2:42 AM
Var rowrowObj = row.cells[0].childNodes[0]; please change this, its throwing an error. instead it should be ===== > var rowObj = row.cells[0].childNodes[0];