Thursday, February 4, 2010

jQuery/Plugin : Problem with Add/Remove row for Tablesorter Plugin

For using the jQuery tablesorter (http://tablesorter.com/docs/ ), the table will not refresh correctly if you use the additional pager plugin.

To solve this problem, you have to add in 2 customised functions/events to take care of the row adding/removal.

Add the following 2 functions to the tablesoter javascript file.

function addRow(table, newRow){

//Rebuild html table from the modified rowsCopy
$.tablesorter.clearTableBody(table);

if (table.config.rowsCopy!=undefined)
$.each(table.config.rowsCopy, function() {
$(table).find('tbody:first').append($(this));
});

//Append new row to the HTML table
$(table).find('tbody:first').append(newRow);

//Update call will rebuild tablesorter.cache from the existing HTML table
$(table).trigger("update");
//With pager plugin, this will call appender function in pager
//In turn, it will redraw the table with pagination
$(table).trigger("appendCache");
//Retain sorting if any
$(table).trigger("sorton",[table.config.sortList]);
}

function removeRow(table, rowId){
//Remove the selected row from pager.rowsCopy
var newRowsCopy = $.grep(table.config.rowsCopy, function(n, i){
return ($(n).attr('id')!=rowId);
});

table.config.rowsCopy = newRowsCopy;

//Rebuild html table from the modified rowsCopy
$.tablesorter.clearTableBody(table);

if (table.config.rowsCopy!=undefined)
$.each(table.config.rowsCopy, function() {
$(table).find('tbody:first').append($(this));
});

//Update call will rebuild tablesorter.cache from the existing HTML table
$(table).trigger("update");
//With pager plugin, this will call appender function in pager
//In turn, it will redraw the table with pagination
$(table).trigger("appendCache");
}



You can bind the functions 2 customised events as follows:
   $this.bind("addRow",function(event,newRow){
addRow(this,newRow);
});

$this.bind("removeRow",function(event,rowId){
removeRow(this,rowId);
});



Finally you can call the events from your page as follows:
  $(sortTable).trigger("removeRow",[id for the row to be removed]);

var newTr = $('<tr><td>New Row</td></tr>');
$(sortTable).trigger("addRow",[newTr]);

1 comment:

  1. hi, I tried your method but my tr don't remove... :-(
    Can you help me ?
    I haven't any javascript error (firebug) and my row don't hide..

    HELPP ! :)

    Thx !

    ReplyDelete