I am trying to create a live-search with jQuery and comma-separated keywords. If I only take the complete string from text-field as keyword, the search works like a charm.
Code (working for single keyword):
jQuery("#artikelfilter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;
// Loop through the comment list
jQuery("#liste-alles li").each(function(){
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
count++;
}
});
// Update the count
var numberItems = count;
jQuery("#filter-count").text("Number of Comments = "+count);
});
What I am trying to do now, is to filter with multiple keywords. I thought about splitting the string into an array and loop through the keywords. The problem is, that I get loads of jQuery events, so the browser can not handle it anymore.
Is there any smart way to make this work?
The code for multiple keywords (not working):
jQuery("#artikelfilter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var string_filter = jQuery(this).val();
var array_filter = string_filter.split(',');
// Loop through the comment list
jQuery("#liste-alles li").each(function(){
jQuery.each( array_filter, function( intValue, currentFilter ) {
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
}
});
});
});
Thank you!
Try this
jQuery.each( array_filter, function( intValue, currentFilter ) {
jQuery("#liste-alles li:contains("+currentFilter +")").show();
jQuery("#liste-alles li:not(:contains("+currentFilter +"))").fadeOut();
});
or this
var regex = new RegExp(filter, "i"));
jQuery.each( array_filter, function( intValue, currentFilter ) {
jQuery("#liste-alles li").filter(function () {return regex.test($(this).text()); }).show();
jQuery("#liste-alles li").filter(function () {return !regex.test($(this).text()); }).fadeOut();
});