Manu
Manu

Reputation: 4500

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 />

Upvotes: 6

Views: 7979

Answers (4)

Slim Fadi
Slim Fadi

Reputation: 1107

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

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

Upvotes: 4

Andy E
Andy E

Reputation: 344527

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).

Upvotes: 4

yscik
yscik

Reputation: 879

If you also want to match for classname fragments (e.g. to show "apple" when typing "ple"), consider using the attribute contains 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();    
}

Upvotes: 3

Jo Albright
Jo Albright

Reputation: 570

Actually, if you are wanting to show the ones that are named with the filter value you will want to use .not() instead of .filter()

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

Upvotes: 0

Related Questions