Monday, February 21, 2011

how to delete specific number of rows using jquery provided by argument

i have a sample code. This will delete entire row if nor args provided. If provided it will delete the given rows.

function deleteTableRows(tableID)
{
        rowsToDel = document.getElementById('getrows').value;
        if(document.getElementById(tableID) !== undefined)
        {
                var tbl = document.getElementById(tableID);
                var deleteAll = false;
                if(rowsToDel ==null || rowsToDel == "")
                {
                        rowsToDel = tbl.rows.length;
                        deleteAll = true;
                }
                if(deleteAll)
                {
                        while(rowsToDel > 0)
                        {
                                tbl.deleteRow(rowsToDel - 1);
                                rowsToDel = tbl.rows.length;
                        }
                }
                else
                {
                        while(rowsToDel > 0)
                        {
                                tbl.deleteRow(rowsToDel - 1);
                                rowsToDel = rowsToDel - 1;
                        }
                }
        }
}

How to do this in jquery

From stackoverflow
  • See a working example

    function deleteTableRows(table, rowsToDelete) {
        table = $(table);
        var rows = table.find('> tbody > tr');
        rows.slice(-(rowsToDelete || rows.length)).remove();
    }
    

    Moved the rowsToDelete parameter inside the function to remove the external dependency on the #getrows element.

    Also, changed the table parameter so we can pass the DOM element, or a selector, or a jQuery wrapped object to select which table.

0 comments:

Post a Comment