Simple real time search and filter using jQuery

Let's say you have a list of HTML elements (div) and you want to implement the search and filter functionality. Here is dead simple example:

Assuming your HTML block looks like the following:

<div>
<input type="text" id="search" placeholder="Type to search">
<button id="search-btn">Search</button>
</div>

<div class="list-partner">
<div class="partner-item">...</div>
        <div class="partner-item">...</div>
        <div class="partner-item">...</div>
</div>

And this javascript snippet will add the magic:

<script>
var rows = jQuery('.list-partner .partner-item');
jQuery('#search-btn').click(function() {
var val = jQuery.trim(jQuery('#search').val()).replace(/ +/g, ' ').toLowerCase();

rows.each(function(){
var itemtxt = jQuery(this).text().replace(/\s+/g, ' ').toLowerCase();
if(itemtxt.indexOf(val) > -1) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
});
</script>

Pretty amazing huh? \m/

Comments