Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide elements based on a filter

I'm new to jquery and I'm trying to do the following : I have a page with lots of images. I added a textbox, with onchange calling this function :

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

}

The point being to only show images that have "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 />
like image 573
Manu Avatar asked Feb 08 '11 14:02

Manu


2 Answers

Use jQuery's .filter() method 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 show elements based on this filter, just swap the places of .hide() and .show() in the code, so that all photos are hidden and then filtered ones are shown (instead of all photos shown and filtered ones hidden).

like image 63
Andy E Avatar answered Sep 20 '22 10:09

Andy E


this way you're filtering classes, if you want to filter text you do this

$(".photo").hide();
$(".photo:contains("+filter+")").show();
like image 20
Slim Fadi Avatar answered Sep 21 '22 10:09

Slim Fadi