James James - 1 year ago 56
HTML Question

jquery show div only if no results returned in search

I have the following code that I need some guidance with please. I need the #no-results element to appear only if no results are found. Currently it shows IF results are found.

$('#no-results').hide();
$('#video-search-text').keyup(function () {
$('.video-search').hide();
$('#no-results').css("display", "none");
var txt = $('#video-search-text').val();

$('.video-search').each(function () {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();

}
else {
$('#no-results').css("display", "block");

}
});

});


I have created the following JSFiddle for convenience. Thanks

Answer Source

Remove the check for no result from inside the for each loop, and place it after the search is complete. like

 $('#no-results').hide();
 $('#video-search-text').keyup(function() {
     $('.video-search').hide();
     $('#no-results').css("display", "none");
     var txt = $('#video-search-text').val();
     var resultCount = 0;
     $('.video-search').each(function() {
         if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
             $(this).show();
             resultCount++;
         }
     });

     if (resultCount == 0) {
         $('#no-results').css("display", "block");
     }

 });