Skip to content

Instantly share code, notes, and snippets.

@brianherbert
Created September 10, 2013 01:03
Show Gist options
  • Save brianherbert/6503696 to your computer and use it in GitHub Desktop.
Save brianherbert/6503696 to your computer and use it in GitHub Desktop.

Revisions

  1. brianherbert created this gist Sep 10, 2013.
    86 changes: 86 additions & 0 deletions filter-table.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,86 @@

    // 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('');
    }
    }
    }

    }