0

I have a PHP page and a table where I fill it up with data from the database. I have a search field on top of the table where I would like to filter rows as I am typing.

Here is my Javascript

$('#system-search').keyup( function() 
{
    var that = this;
    // affect all table rows on in systems table
    var tableBody = $('.table table-filter tbody');
    var tableRowsClass = $('.table table-filter tbody tr');
    $('.search-sf').remove();
    tableRowsClass.each( function(i, val) 
    {
        //Lower text for case insensitive
        var rowText = $(val).text().toLowerCase();
        var inputText = $(that).val().toLowerCase();
        if(inputText != '')
        {
            $('.search-query-sf').remove();
            tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
            + $(that).val()
            + '"</strong></td></tr>');
        }
        else
        {
            $('.search-query-sf').remove();
        }
        if( rowText.indexOf( inputText ) == -1 )
        {
            //hide rows
            tableRowsClass.eq(i).hide();
        }
        else
        {
            $('.search-sf').remove();
            tableRowsClass.eq(i).show();
        }
    });
    //all tr elements are hidden
    if(tableRowsClass.children(':visible').length == 0)
    {
        tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
    }
});

Sorry for the bad code and formatting I can't seem to understand how to format it properly..

Shadow
  • 33,525
  • 10
  • 51
  • 64
  • 2
    Can you describe the current behavior if this code? What exactly is the problem/question? – Bane Bojanić Aug 08 '17 at 19:48
  • I am trying to achieve exactly the same thing as here : https://bootsnipp.com/snippets/featured/js-table-filter-simple-insensitive . When I start typing in the search box it will filter out results – user2996891 Aug 08 '17 at 20:00
  • client (javascript) filtering on potentially big table is bad pattern – Jacek Cz Aug 08 '17 at 20:06
  • Then how do I filter out results in a more efficient way? And it isn't a big table really. Max 20-30 rows – user2996891 Aug 08 '17 at 20:08

1 Answers1

0

https://stackoverflow.com/a/19696936/1406155

You are using a bit too much code for that. First place an input field like this

<input type="text" id="search" placeholder="Search">

and use the below function for search

$("#search").keyup(function () {
    var value = this.value.toLowerCase().trim();

    $("table tr").each(function (index) {
        if (!index) return;
        $(this).find("td").each(function () {
            var id = $(this).text().toLowerCase().trim();
            var not_found = (id.indexOf(value) == -1);
            $(this).closest('tr').toggle(!not_found);
            return not_found;
        });
    });
});
in.k
  • 102
  • 2
  • 12