JQuery methods for dynamically adding and deleting table rows

  • 2020-05-12 02:10:12
  • OfStack

This example demonstrates how JQuery dynamically adds and removes table rows. Share with you for your reference. The specific analysis is as follows:

Yesterday do page table row dynamic add and delete, looked at countless introductions, found a good east, JQuery. It's really easy to implement, and this is one of the ways I use our platform.

// Record the number of added rows 
var areaCount=1;
// Record the actual number of rows in the table
var rowCount=1;
// To delete a template html
var delRowTemplete = "<td><a href='javascript:void(0);' class='content_del' onclick='deleteBatchRow(this)'> delete </a></td>";
// Table row template
var addRowTemplete= "";
$(function(){
// First take out the template that you want to clone, the template line <tr>id for rowTemplete_0
addRowTemplete=  $("#rowTemplete_0").html();
});
// Increase the line
function addBatchRow(type){
var templete = $("<tr id='rowTemplete_"+areaCount+"'></tr>");
// Increasing the number, replacing it tr or td in [0] , _0 or (0) To prevent id The same , This design is mainly for the convenience of the background value
templete = templete.append(addRowTemplete.replace(/\[0\]/g,"["+areaCount+"]").replace(/_0/g,"_"+areaCount).
replace("processStat(\"0\")","processStat("+areaCount+")"));
// To find the last 1 The row in which the bar exists , After that splice 1 line
var flag = false;
for(var i=areaCount-1;i>=0;i--){
if($("#rowTemplete_"+i).length>0){ $("#rowTemplete_"+i).after(templete.append(delRowTemplete));
break;}
}
// Count to add 1
areaCount++; rowCount++;
}
// Delete rows
function deleteBatchRow(obj){
if(rowCount>1) {
$(obj).parents("tr").remove();
rowCount--;
} else alert(" Keep at least 1 line ");// If all the lines are deleted, then there is no way to add the line, the template line has been deleted
}
// Get a number
function getAreaCount(){
return rowCount;
}

The background is also relatively easy to use, FormBean in the definition of array variables to get and set, very convenient.

I hope this article is helpful to you in jQuery programming.


Related articles: