Created
September 10, 2013 01:03
-
-
Save brianherbert/6503696 to your computer and use it in GitHub Desktop.
Filters a table based on data attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This script is for supporting forms with searchable filters to show/hide rows of the table | |
$(document).ready(function() { | |
root.filters = []; | |
$('.filter-table-filters').find('td').each(function(i) { | |
var tdKey = 'td'+i; | |
$(this).data('filters',tdKey); | |
if($(this).find('input').length) { | |
// If we have an input field here | |
root.filters.push($(this).find('input')); | |
$(this).addClass('filter-trigger'); | |
}else if($(this).find('select').length) { | |
// If we have a select, dropdown here | |
root.filters.push($(this).find('select')); | |
$(this).addClass('filter-trigger'); | |
} | |
}); | |
$(document).on('keyup change','.filter-trigger',function(e){ | |
root.filterTableFilter(); | |
}); | |
}); | |
root.filterTableFilter = function() { | |
// Where the content is, son | |
var tbody = $('.filter-table > tbody'); | |
var rows = $(tbody).find('tr.filter-table-row'); | |
// First hide everything. Tabula Rasa. | |
$(rows).hide(); | |
$('.filter-match').removeClass('filter-match'); | |
// Reset matches to 0 | |
$(rows).data('matches',0); | |
// Loop through our filters | |
$.each(root.filters,function(i,filter){ | |
var type = $(filter).prop("tagName").toLowerCase(); // input / select | |
var col = $(filter).data('filter-col'); | |
var search = $.trim($(filter).val()); | |
if(type == 'input') { | |
if(search == ''){ | |
// Searching for nothing, so match all | |
$(rows).find("td[data-filter-col="+col+"]").addClass('filter-match'); | |
}else{ | |
$(rows).find("td[data-filter-col="+col+"]:contains('"+search+"')").addClass('filter-match'); | |
} | |
}else if(type == 'select') { | |
var selectAllVal = $(filter).data('filter-select-all'); | |
if(search == selectAllVal){ | |
$(rows).find("td[data-filter-col="+col+"]").addClass('filter-match'); | |
}else{ | |
$(rows).find("td[data-filter-col="+col+"][data-filter-select-val="+search+"]").addClass('filter-match'); | |
} | |
} | |
}); | |
$.each(rows,function(i,row){ | |
// If it matches all of our filters, show it! | |
if($(row).find('.filter-match').length == root.filters.length) { | |
$(this).show(); | |
} | |
}); | |
if($('.filter-count').length) { | |
var count = $('tr.filter-table-row:visible').length; | |
$('.filter-count').text(count); | |
if($('.filter-count-plural').length) { | |
if(count != 1) { | |
$('.filter-count-plural').text('s'); | |
}else{ | |
$('.filter-count-plural').text(''); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment