Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display when no results found on keyup event

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.

like image 658
R U Avatar asked Oct 31 '22 03:10

R U


1 Answers

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>
like image 59
BenG Avatar answered Nov 13 '22 18:11

BenG