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 />
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).
this way you're filtering classes, if you want to filter text you do this
$(".photo").hide();
$(".photo:contains("+filter+")").show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With