Reputation: 22217
I try to filter data by using jQuery/HTML selector like
$("li[data-filter*='keyword']")
But this cannot filter and get same result "keyword1 keyword2" and "keyword2 keyword1" , Do you understand ?
I will give you demo..
HTML :
<input>
<li data-filter="apple pie gummi bears gummi bears john">
Apple pie gummi bears gummi bears John
</li>
<li data-filter="oat cake chocolate bar chupa chups dessert tootsie">
Oat cake chocolate bar chupa chups dessert tootsie
</li>
<li data-filter="jujubes cookie sugar plum lemon drops candy">
Jujubes cookie sugar plum lemon drops candy
</li>
jQuery :
var filter_timer;
$("input").keypress(function() {
clearTimeout(filter_timer);
filter_timer=setTimeout(function(){
filter();
},500);
});
function filter() {
var keyword = $("input").val();
if($("li[data-filter*='"+keyword+"']").length) {
$("li").animate({opacity:0.4}).css({"text-decoration":"line-through"});
$("li[data-filter*='"+keyword+"']").animate({opacity:1}).css({"text-decoration":"blink"});
}else{
$("li").animate({opacity:1},function(){$("li").removeAttr("style")});}
}
Playground : http://jsfiddle.net/9eaXD/
How can I get same result when I searching apple pie and pie apple or apple gummi pei
Upvotes: 2
Views: 1537
Reputation: 298532
What you're trying to do can't be accomplished with attribute selectors. [data-filter*="apple pie"]
matches only elements whose data-filter
attribute contains exactly the string apple pie
.
You should use .filter()
instead:
$("input").keypress(function() {
var keywords = $(this).val().split(' ');
$('li').removeClass('matched');
$("li[data-filter]").filter(function() {
var filters = $(this).data('filter').split(' ');
for (var i = 0; i < keywords.length; i++) {
var keyword = keywords[i];
if (filters.indexOf(keyword) == -1) {
return false;
}
}
return true;
}).addClass('matched');
});
Demo: http://jsfiddle.net/9eaXD/8/
You could optimize this a little more by creating the filters
array for each element on page load:
$("li[data-filter]").filter(function() {
var $this = $(this);
$this.data('filter', $this.data('filter').split(' '));
});
Upvotes: 3