KYSSE
KYSSE

Reputation: 385

If all children are "hidden" show <p> tag saying "No results found" using jQuery

I am creating a glossary page with page filtering based on a searchable term. I am doing this all in jQuery with a simple script.

$("#txtSearch").on('keyup', function() {
    var search = $(this).val().toLowerCase();
    //Go through each list item and hide if not match search

    $(".list-group-item").each(function() {
        if ($(this).html().toLowerCase().indexOf(search) != -1) {
            $(this).show();
        } else {
            $(this).hide();
        }

    });
});
$(document).keyup(function(event) {
    if ($("input#txtSearch").is(":focus") && event.key == "Enter") {
        $('html, body').animate({
            scrollTop: $("#gloss-list-ul").offset().top + (-40)
        }, 600);
    }
});

Right now it works great. But if someone types in a word that returns no results. It shows nothing as expected However how can i display some text that says "Nothing in our index matches your term" when this happens?

Upvotes: 0

Views: 50

Answers (1)

Shivendra Singh
Shivendra Singh

Reputation: 3006

Add a div to display the error message.

In jQuery Create a variable call search_result. By default make it false. If getting the result make it true.

search_result is false - display the error message

search_result is true - error message will empty

 $("#txtSearch").on('keyup', function() {
        var search_result = false; //Create a variable call var search_result
        var search = $(this).val().toLowerCase();
        //Go through each list item and hide if not match search

        $(".list-group-item").each(function() {
        if ($(this).html().toLowerCase().indexOf(search) != -1) {
        $(this).show();
        search_result = true; //If getting the result make it true.
        }
        else {
        $(this).hide();  

        }

        if(search_result) {  //search_result is true  - Error message will empty
            $('.display_error_message').html('');
        }else{  //search_result is false - display the error message
            $('.display_error_message').html('Nothing in our index matches your term');
        }

        });
        });

DEMO

Upvotes: 1

Related Questions