Created
September 18, 2012 11:30
-
-
Save gabeidx/3742692 to your computer and use it in GitHub Desktop.
Filter table rows as you type on a input field.
This file contains hidden or 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
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fino