Filter by <li> text
HTML
<div id="container">
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<ul id="list">
<li data-style="Long Sleeves, V-Neck" data-color="Black">Item 1</li>
<li data-style="Crew Neck, Short Sleeves" data-color="Blue, Red">Item 2</li>
<li data-style="Sleeveless, V-Neck" data-color="Black & White">Item 3</li>
<li data-style="Crew Neck" data-color="Black">Item 4</li>
<li data-style="V-Neck" data-color="Black">Item 5</li>
<li data-style="Short Sleeves" data-color="Red">Item 6</li>
<li data-style="Sleeveless" data-color="Black">Item 7</li>
</ul>
</div>
CSS
ul {
list-style: none;
}
JavaScript
$(document).ready(function () {
//default each <li> to visible
$('#list li').addClass('visible');
//overrides CSS display:none property so only users w/ JS will see the filter box
$('#search').show();
$('#filter').keyup(function(event) {
//if esc is pressed or nothing is entered
if (event.keyCode == 27 || $(this).val() == '') {
//if esc is pressed we want to clear the value of search box
$(this).val('');
// All <li> should be visible if there is no search criteria
$('#list li').removeClass('visible').show().addClass('visible');
}
//if there is text, lets filter
else {
filter('#list li', $(this).val());
}
});
});
//filter results based on query
function filter(selector, query) {
query = $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex
$(selector).each(function() {
alert("in search");
($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
});
}