There is a dropdown in which the user selects a specific position (in this case, the ID is selected). There are also containers that have a data-filter attribute, which, depending on the category, also have an id. We have a dropdown:

<select class="filter"> <option value=1>Name 1</option> <option value=2>Name 2</option> <option value=3>Name 3</option> </select> 

One of the containers that need to be filtered by the data-filter attribute:

 <div class="item" data-filter=2>container</div> 

There are many such containers. I tried to use the .item selector to run through the each () loop and set the condition in which the containers will be .hide () or .show (). This turned out to be expensive in terms of performance. Then I turned to the filter () function.

 var valuee = $(this).val(); // тут извлекаем значение дропдауна,который выбрал пользователь $('.item').filter(function(index){ return $( this ).data( "filter" ) === valuee; }); 

Does not work. Apparently the problem is in the filter () method, but I don’t catch up with exactly what. How can I rewrite this function to make it work?

  • one
    Your case is one of the rather rare cases where you can fully reproduce the problem in your question using the "Fragment of code on ..." button of the editor to facilitate the task to the person who wants to help you. Instead, you included in your question non-working scraps of html and javascript, leaving us to guess how fully they reflect the real state of things. - Igor
  • 2
    Specifically to your problem (based on the above code): $().filter - does not hide / show DOM elements, but returns a wrapper object around a selection of elements. $('.item').filter(...).hide(); - Igor
  • You are right-adding .hide (); at the end allows you to hide unnecessary items. thanks to the explanation about the wrapper, I understood what my fault was. thanks - Iga Nov.

3 answers 3

The filter method returns the filtered collection. With the elements themselves, nothing happens.

Therefore a challenge

 $('.item').filter(function(index){ return $( this ).data( "filter" ) === valuee; }); 

I returned the necessary elements, but since no actions are taken with the resulting collection, accordingly there is no result either.

    You have an error here:

     return $(this).data("filter") === valuee; 

    It is necessary so:

     return $( this ).data( "filter" ) == valuee; 

    Because $(this).val(); returns the string a $(this).data("filter") number.

    Example

      After experimenting, I got the desired result by typing when I screwed the .css () method to the filter () method. It works, but I still don’t understand how I think there are any other solutions without screwing inline styles. Ready to listen to any comments and suggestions)

       var valuee = parseInt($(this).val()); $('.item').filter(function () { return $(this).data("filter") != valuee; }).css({'display': 'none'});