Skip to content

Instantly share code, notes, and snippets.

@gabeidx
Created September 18, 2012 11:30
Show Gist options
  • Save gabeidx/3742692 to your computer and use it in GitHub Desktop.
Save gabeidx/3742692 to your computer and use it in GitHub Desktop.
Filter table rows as you type on a input field.
/**
* 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);
@brunopulis
Copy link

Fino

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment