Home > Software engineering >  How to show a message when no results are found
How to show a message when no results are found

Time:10-09

How would I adapt this code to show a <div>No Results Found</div> on the page when no results are found?

I've got this simple image gallery with an input to filter results based on the contents of the data-filter attribute:

<input type="text" name="filter" placeholder="Filter" id="filter">
<div class="results-gallery">
    <div class="gallery-thumbnail" data-filter="Apple">image</div>
    <div class="gallery-thumbnail" data-filter="Orange">image</div>
    <div class="gallery-thumbnail" data-filter="Banana">image</div>
</div>

And the jQuery:

$("#filter").keyup(function() {
    var value = $(this).val().toLowerCase();
    $(".gallery-thumbnail").filter(function() {
        $(this).toggle($(this).attr("data-filter").toLowerCase().indexOf(value) > -1);
    });
});

CodePudding user response:

You could use the same method and do it like this:

$(document).ready( function(){
    $("#filter").keyup( function(){
        var value = $(this).val().toLowerCase();
        $(".gallery-thumbnail").filter(function() {
            $(this).toggle($(this).attr("data-filter").toLowerCase().indexOf(value) > -1);
        });
        $('.noresult').toggle($(".gallery-thumbnail:visible").length == 0)
    });
});

Demo

CodePudding user response:

You put 'No Results' div on the page, with a class which initially defaults it to be hidden (display:none). If your filter returns no results, you add a class to the div to show it (display: block). When the filter is cleared, and you have results again, you remove the 'show' class, reverting it back to it's default 'hidden' state.

  • Related