JavaScript Based implementation to dynamically add and delete table rows

  • 2020-12-13 18:50:56
  • OfStack

Another dynamic control table, JavaScript is used to dynamically generate table rows, table columns, and dynamically delete these rows, rows, etc. After running the code, click the corresponding function button to achieve the corresponding table operation function.

1.jsp


<table id="viewTabs">
<thead>
<tr>
<th> The product name </th>
<th> Serial number </th>
<th> The number of </th>
<th> The weight of the </th>
<th> operation </th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="productName" type="text"></td>
<td><input name="productNumber" type="text"></td>
<td><input name="quantity" type="text"></td>
<td><input name="weight" type="text"></td>
<td></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addTable();" style="margin-left: 750px;"> Add the line </button>

2.js


// Add the line 
function addTable(){
var tab=document.getElementById("viewTabs"); // Get form 
var colsNum=tab.rows.item(0).cells.length; // The number of columns in the table 
// The current number of rows in the table  
var num=document.getElementById("viewTabs").rows.length;
var rownum=num;
tab.insertRow(rownum);
for(var i=0;i<4; i++)
{
tab.rows[rownum].insertCell(i);// Insert column 
if(i==0){
tab.rows[rownum].cells[i].innerHTML=
'<input name="productName" type="text"/>';
}else if(i==1){
tab.rows[rownum].cells[i].innerHTML='<input name="productNumber" type="text"/>';
}else if(i==2){
tab.rows[rownum].cells[i].innerHTML='<input name="quantity" type="text"/>';
}else{
tab.rows[rownum].cells[i].innerHTML='<input name="weight" type="text"/>';
}
}
tab.rows[rownum].insertCell(i);
tab.rows[rownum].cells[i].innerHTML='<a href="#" onclick="delRow(this)"> Delete rows </a>';
}
// Delete rows 
function delRow(obj)
{
var Row=obj.parentNode;
var Row=obj.parentNode; //tr
while(Row.tagName.toLowerCase()!="tr")
{
Row=Row.parentNode;
}
Row.parentNode.removeChild(Row); // Delete rows 
}

Above is the JavaScript implementation of dynamic adding and deleting table rows shared by this site, hoping to help you.


Related articles: