I have multiple classes called post-content
on div
and have a search box, who's event is fired on keyup
. If there's no matching result, I'd like to display 'No results match'
$('.post-content').each(function() {
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('#search-criteria').on('keyup', function() {
var searchTerm = $(this).val().toLowerCase();
$('.post-content').each(function() {
if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0) {
$(this).show();
} else {
$(this).hide();
}
});
});
I tried creating the element inside the else block, but it seems to fire everytime the key is pressed, thus printing the entire page with the event.
Here is a simpler way.
Hide all then show the relevant posts.
$('.post-content').each(function() {
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('#search-criteria').on('keyup', function() {
var searchTerm = $(this).val().toLowerCase();
$('.post-content').hide();
if (searchTerm) {
var matches = $('.post-content').filter('[data-search-term *= ' + searchTerm + ']');
$('.no-match').toggle(matches.length == 0)
matches.show();
}
});
.no-match {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<div class=post-content>aaaaaaaa</div>
<div class=post-content>bbbbbbbb</div>
<div class=post-content>aaaaaaaa</div>
<div class=post-content>bbbbbbbb</div>
<div class=post-content>aaaaaaaa</div>
<div class=post-content>bbbbbbbb</div>
<div class="no-match">No Matches</div>
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