Skip to content

Instantly share code, notes, and snippets.

@blackjk3
Created May 16, 2012 18:10
Show Gist options
  • Save blackjk3/2712709 to your computer and use it in GitHub Desktop.
Save blackjk3/2712709 to your computer and use it in GitHub Desktop.
Table Filter
// Define AHC object if it doesn't already exist
var AHC = AHC || {};
AHC.TableFilter = ( function(){
var TableFilter = function(tbl, col) {
this.table = tbl;
this.columns = col;
this.textValue = (document.getElementsByTagName("body")[0].textContent !== undefined) ? 'textContent' : 'innerText';
};
TableFilter.prototype.doFilter = function(str) {
var phrase = str.replace(/\s+/g, ' ').toLowerCase();
var tbl_rows, tbl_cells, tbl_col, row_len=0, col_len=0, matched_row=false;
if(phrase.length !== 0) {
// Get tbody
tbl_rows = this.table.tBodies[0].rows;
// Cache row and column lengths.
row_len = tbl_rows.length;
col_len = this.columns.length;
tbl_col = this.columns;
// Loop through rows.
for(var i=0; i < row_len; i++) {
matched_row = false;
tbl_cells = tbl_rows[i].cells;
// Loop through columns and check
for(var j=0; j < col_len; j++) {
if (tbl_cells[tbl_col[j]][this.textValue].toLowerCase().indexOf(phrase) != -1) {
// Found it!
matched_row = true;
break;
}
}
// Hide / Show row.
if(matched_row) {
tbl_rows[i].style.display = "";
} else {
tbl_rows[i].style.display = "none";
}
}
}
};
TableFilter.prototype.clear = function() {
var tbl_rows,row_len=0;
tbl_rows = this.table.tBodies[0].rows;
row_len = tbl_rows.length;
for(var i=0; i < row_len; i++) {
tbl_rows[i].style.display = "";
}
};
return function(tbl, col) {
return new TableFilter(tbl, col);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment