Tilak raj Tilak raj - 2 months ago 10
jQuery Question

Show the filtered items jquery

I am using jquery .filter() to filter certain products inside my page.The Dom structure looks like this..

<body>
<ul class='products'>
<li class='product' data-company="something" data-shape="cake" data-flavour="something"></li>
.
.
.
.
.
<li class='product' data-company="something" data-shape="cake" data-flavour="something"></li>
</ul>
</body>


My filters contains check boxes , so if anyone is checked, it calls my class that initiates my filter function.

My filter function looks something likes this
this.filterGridProducts = function() {
//hide all
_this.products.hide();
var filteredProducts = _this.variants;
//filter by colour, size, shape etc

var filterAttributes = $('input[type="checkbox"]');
var selectedFiltersValues = [];
// for each attribute check the corresponding attribute filters selected
filterAttributes.each(function(){
if(this.checked)
{
var currentFilter = $(this);
console.log(currentFilter);
selectedFiltersValues.push("[data-" + currentFilter.attr('name') + "='" + currentFilter.val() + "']");
filteredProducts = filteredProducts.filter(selectedFiltersValues.join(','));
}
});
//console.log(filteredProducts.parent());
filteredProducts.parent().show();

};


filteredProducts.parent().show();
This line shows me all the results that i don't even want.

when i
console.log
the
filteredProducts
, it shows me the ones that i need , what should i do in order to show me the ones that
filterProducts
contains?

Note: whenever the page is loaded , all the items are displayed.If anyone needs something else please let me know.

Answer

You could do something like this

  filteredProducts.parent().show();
  $('ul.products').children().not(filteredProducts).hide();

What's actually happening is that it's showing the parent element and all of it's child elements as well.You could use .not() present in jquery api for selecting everyone except the one's you want and then using hide on those selected items.I don't know about any other jquery function to output the selected items directly but for your situation this workaround fits best.

I am open to any other suggestions as well.

Comments