fredyounan
1/5/2014 - 12:38 PM

Filter table rows as you type

Filter table rows as you type

/**
 * Filter table rows as you type
 *
 * == How to use ==
 * Just add the script to the page and, on the input element,
 * add the data-filter attibute with the selector to the table.
 * <input type="search" data-filter="#tableID">
 *
 * == Acknowledgements ==
 * This was inspired by jresig's liveUpdate plugin used on jQuery's
 * API Docs. I needed the same thing but for table rows.
 *
 */
;(function($) {
    "use strict";
    var inputs = $('input[data-filter]'),
        input = {},
        table = {},
        rows = {},
        cache = {},
        filter = function(){
            var term = $.trim( input.val().toLowerCase() )
            
            if ( !term ) {
                rows.show()
            } else {
                rows.hide()
                cache.each( function(i){
                    if ( this.indexOf( term ) > -1 )
                        $( rows[i] ).show();
                })
            }
        }

    inputs.each(function(){
        input = $(this)
        table = $(input.data('filter'))

        if ( table.length ) {
            rows = table.find('tbody tr')
            cache = rows.map(function(){    
                return $(this).text().toLowerCase()
            })
            input.on('keyup', filter)
        }
    })
})(jQuery);