I have a sizeable table containing 27 columns and anywhere from 5 to 100 rows. To switch between a simple view showing the first 5 columns and an expert view showing all 27 columns, I have implemented a mode switch (checkbox).
Currently, I am using the following jQuery method to facilitate the mode switch:
$("#ToggleTableCells").click(function(){
if($(this).is(':checked')){
$(".hiddencells").removeClass("hiddencells").addClass("showcells");
}else{
$(".showcells").removeClass("showcells").addClass("hiddencells");
}
});
However, toggling the modes in a table with a large number of rows is taking longer than desired. Is there a quicker way to replace classes or optimize the provided code?
While the css gt method partially works, toggling back hides all table rows:
$("#toggleTableCells").change(function() {
if(this.checked){
$("#Table tr td:gt(4), #Table tr th:gt(4)").show();
}else{
$("#Table tr td:gt(4), #Table tr th:gt(4)").hide();
}
});
It appears that the first solution offered by Nick is the most effective:
$("#ToggleTableCells").change(function(){
if(this.checked){
$(".hiddencells").toggleClass("hiddencells showcells");
}else{
$(".showcells").toggleClass("showcells hiddencells");
}
});
Experimenting with a combination of Nick and Nikita's solutions did not yield a significant speed enhancement.
As a final solution, I have implemented the following:
var cells = $();
$("#Table tr").each(function() { cells = cells.add($(this).children(":gt(4)")); });
$("#ToggleTableCells").change(function(){
cells.toggle(this.checked);
});