Wednesday, March 28, 2012

Delete Table Rows

To delete selected rows from a table, obviously, we need to add checkboxes to every table row. When a checkbox is checked, it means that that particular row will be deleted. Also, we need some method by which we could identify a selected row. The value attribute of a checkbox is a very good candidate for that. It will equal a row index. As you know, row indices start at 0, so the value of first row checkbox will equal 0, the value of the second row checkbox will equal 1, and so on.
Now, we can write a function to be called from the Delete button:
First, we get a reference to the table:

var table = document.getElementById("myTable");

Then, we get a reference to the array of checkboxes in the table:

var checks = table.getElementsByTagName("input");

Normally, this array will contain all the inputs in the table, and we would have to use the type property to get a reference to desired elements. However, if we are sure that there are no other inputs in the table other than the checkboxes, we can skip this check.
Now, we iterate through all the checkboxes. If the checked property is true, we obtain the index of a row which is contained in the checkbox value property, and delete this row. Also, we have iterate backwards, because otherwise removing a row changes the subsequent row index by -1. Iterating backwards preserves our indices.

for(var i= checks.length-1; i>=0; i --){
 if(checks[i].checked){
  var indx =  checks[i].value;
  table.deleteRow(indx);
 }
}

The next step resets the values of the checkboxes to make sure that they correspond to the new row indices.

var checks = table.getElementsByTagName("input");
for(var i= 0; i < checks.length; i++){
 checks[i].value=i;
}

Here is the complete function listing :

function deleteRows(){
 var table = document.getElementById("myTable");
 var checks = table.getElementsByTagName("input");

 for(var i= checks.length-1; i>=0; i --){
  if(checks[i].checked){
   var indx =  checks[i].value;
   table.deleteRow(indx);
  }
 }
 var checks = table.getElementsByTagName("input");
 for(var i= 0; i < checks.length; i++){
  checks[i].value=i;
 }
}

No comments:

Post a Comment