Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active October 14, 2015 00:18
Show Gist options
  • Save aklump/4278992 to your computer and use it in GitHub Desktop.
Save aklump/4278992 to your computer and use it in GitHub Desktop.
Create a searchable list by textfield jQuery Plugin
/**
* Create a searchable list by textfield jQuery Plugin
*
* @param object $input
* A jQuery object of a textfield to use as the search box
* @param options
* code: the ascii code of the key to use for lookup; when this is pressed
the list will be searched, defaults to 13 for the Return key.
* auto: min length needed before it will autosearch, for large lists
setting this too low results in poor performance. Set this to 0 to turn off
autosubmit.
*
* @return $(this)
*
* Attach this to a list and pass it an input to get a searchable list by the
input field e.g.
@code
$('ul.list').listSearchFilter($('input.search'));
@endcode
*
*
* @author Aaron Klump, In the Loft Studios, LLC
* @see http://www.intheloftstudios.com
* @see http://gist.github.com/4278992
*/
(function($) {
$.fn.listSearchFilter = function($input, options) {
var $list = $(this);
var settings = $.extend({
'code' : 13,
'auto' : 6
}, options);
/**
* Filter the list with a needle
*/
var filter = function(needle) {
var $items = $list.find('li');
// Reset the list if needle is empty
if (!needle) {
$items.show();
return;
}
$items
.hide()
.filter(function() {
return $(this).text().indexOf(needle) !== -1;
}).show();
};
// Handler of the input
$input.keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var needle = $(this).val();
if((settings.auto && needle.length >= settings.auto) ||
code === settings.code) {
filter(needle);
}
});
return $(this);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment