Skip to content

Instantly share code, notes, and snippets.

@shaundon
Last active December 13, 2015 22:28
Show Gist options
  • Save shaundon/4984247 to your computer and use it in GitHub Desktop.
Save shaundon/4984247 to your computer and use it in GitHub Desktop.
Function for searching the text of some elements and hiding elements that don't match the search terms. Prerequisites: jQuery, and a CSS class 'visible' that allows your elements to display (this is then toggled on/off)
function FilterResults(query) {
// Remove whitespace.
query = $.trim(query);
// Add an 'OR' for regex syntax.
query = query.replace(/ /gi '|');
$('selector for each element to search').each(function () {
// Search the text of the element with a regex.
($(this).text().search(new RegExp(query, "i")) < 0) ?
// If this element doesn't match the regex, hide it.
$(this).hide().removeClass('visible') :
// Otherwise show it.
$(this).show().addClass('visible');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment