JQuery is looking for everything when empty

I make a search button on my website, but I have a problem when I delete the text and the text field is empty, nothing is displayed, I want that if the text field is empty, all Items will be displayed. How can i do this?

$(document).ready(function () {
    $("#searchdata tr").show();

    $('#searchdata tr').each(function () { 
        $(this).attr('data-text', function () {
            return $(this).text().toLowerCase();
        });
    });

    $('#searchbtn').bind('change keypress  keyup change', function () {
        $("#searchdata tr").hide();
        $('#searchdata tr[data-text*="' + $.trim($(this).val().toLowerCase()) + '"]').show();           
    });
});

And my website: www.ledai.ae/locations

+4
source share
2 answers

You can change your logic to check if a value is set and act accordingly. Try the following:

$('#searchbtn').bind('change keypress  keyup change', function () {
    var searchString = $.trim($(this).val().toLowerCase());
    if (searchString != '') {
        $("#searchdata tr").hide().filter('tr[data-text*="' + searchString + '"]').show();     
    } else {
        $("#searchdata tr").show();
    }      
});
+2
source

Instead $("#searchdata tr").hide();you can use toggle():

$("#searchdata tr").toggle(!this.value);

You could trim it to handle input, getting only empty spaces:

$("#searchdata tr").toggle(!$.trim(this.value));
+1
source

All Articles