Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete last row in table

Tags:

javascript

I've got a simple question, I want to delete the last row in a table, I copied one function that deletes the checked one though:

function deleterow(tableID) {
    try {
         var table = document.getElementById(tableID);
         var rowCount = table.rows.length;

         for(var i=1; i<rowCount; i++) {
              var row = table.rows[i];
              var chkbox = row.cells[0].childNodes[0];
              if(null != chkbox && true == chkbox.checked) {
                   table.deleteRow(row);
                   rowCount--;
                   i--;
              }
         }
    }catch(e) {
        alert(e);
    }
}

How do I change it, so that it will delete only the last row each time it's called? Thank you all for the help! I really appreciate it!

like image 784
Bato Dor Avatar asked May 21 '12 14:05

Bato Dor


2 Answers

the deleteRow function takes an index, pass it count - 1.

http://jsfiddle.net/jbabey/HEDNZ/

function deleterow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    table.deleteRow(rowCount -1);
}
like image 189
jbabey Avatar answered Oct 08 '22 22:10

jbabey


Why not just use:

function deleterow(tableID) {
    var table = document.getElementById(tableID);
    table.deleteRow(-1);
}
like image 2
t c Avatar answered Oct 08 '22 23:10

t c