Sample code to dynamically add and delete table rows using js

  • 2020-03-30 00:55:41
  • OfStack

As follows:


//Dynamically add rows
function addRow(){
   var table = document.getElementById("tableID");
   var newRow = table.insertRow(); //Create a new line
   var newCell1 = newRow.insertCell(); //Create a new cell
   newCell.innerHTML = "" ;  //The contents of the cell
   newCell.setAttribute("align","center"); //Set the location
}
//Dynamically delete rows
function deleteRow(){
   var rowIndex = event.srcElement.parentElement.parentElement.rowIndex;
   var styles = document.getElementById("tableID");
   styles.deleteRow(rowIndex);
}
<html>
<head>
<title></title>
</head>
<body>
<table id="testTbl" border=1>
<tr>
<td>
 The product name 
</td>
<td>
 Product quantity 
</td>
<td>
 The product is monovalent 
</td>
</tr>
<tr>
<td>
<select name="a">
   <option value=" electronic "> electronic </option>
   <option value=" Electrical appliances "> Electrical appliances </option>
</select></td>
<td>
    <input type="text" name="b">
     </td>
<td>
    <input type="text" name="c">
     </td>
</td>
</table>
<input type="button" name="Submit2" value=" add " onclick="addRow()">
<script>
function addRow(){
//Add the line
var newTr = testTbl.insertRow();
//Add columns
var newTd0 = newTr.insertCell();
var newTd1 = newTr.insertCell();
var newTd2 = newTr.insertCell();
var newTd3 = newTr.insertCell();
//Sets the column contents and properties
newTd0.innerText = document.all("a").options[document.all("a").selectedIndex].text;
newTd1.innerText = document.all("b").value;
newTd2.innerText = document.all("c").value;
newTd3.innerHTML= '<input type="button" name="del" value=" delete " onclick="del(this)">';
}
function del(o)
{
var   t=document.getElementById('testTbl');
t.deleteRow(o.parentNode.parentNode.rowIndex)
}
</script>
</body>
</html>


Related articles: