Hide filter based items

I am new to jquery and I am trying to do the following: I have a page with a lot of images. I added a text box with onchange calling this function:

function filter() { var filter = $("#filter").val() $('.photo').show(); if (filter != '') $('.photo').find('.'+filter).hide(); } 

The point is to show only images that have a โ€œfilterโ€ somewhere in their class name.

EDIT

 <a name="test"></a> <h3>Tests</h3><br /> <img class="photo livre_gang_leader.jpg" src="/images/test/livre_gang_leader.jpg" /> <img class="photo stephen_king_fatal.jpg" src="/images/test/stephen_king_fatal.jpg" /> <img class="photo livres_millenium.jpg" src="/images/test/livres_millenium.jpg" /></a> <img class="photo martin_page_stupide.jpg" src="/images/test/martin_page_stupide.jpg" /> <img class="photo Civilization-V-Title.jpg" src="/images/test/Civilization-V-Title.jpg" /> <br /><br /> 

EDIT

 <form onSubmit="javascript:filter()"> <input type="textbox" placeholder="Filtre" id="filter" /> <input type="submit" value="filtrer"> </form><br /> 
+4
source share
4 answers

If you also want to match classname for fragments (for example, to display "apple" when typing "ple"), consider using the attribute selector '[class*="'+filter+'"]' . Combined with the answers above:

 function filter() { var filter = $("#filter").val(); var photos = $('.photo'); photos.show(); if (filter != '') photos.not('[class*="'+filter+'"]').hide(); } 
+3
source

Use jQuery .filter() instead of .find() :

 function filter() { var filter = $("#filter").val(), photos = $('.photo'); // don't forget to cache your selectors! photos.show(); if (filter != '') photos.filter('.'+filter).hide(); } 

If you want to display elements based on this filter, simply swap .hide() and .show() in the code so that all photos are hidden and then filtered (instead of all the photos shown and filtered, are hidden).

+4
source

that way you filter classes if you want to filter the text you do this

 $(".photo").hide(); $(".photo:contains("+filter+")").show(); 
+3
source

In fact, if you want to show those that are specified using a filter value, you want to use .not() instead of .filter()

 function filter() { var filter = $("#filter").val(); $('.photo').show(); if (filter != '') $('.photo').not('.'+filter).hide(); } 
0
source

Source: https://habr.com/ru/post/1338869/


All Articles