Real-time search with jQuery

0

I have the following code to do a real-time search with jQuery, searching for values inside a table:

$(document).ready(function () {

    $(".nada").hide();

    var $rows = $('.linhas');
    $('#search').keyup(function () {

        var val = '^(?=.*\b' + $.trim($(this).val()).split(/\s+/).join('\b)(?=.*\b') + ').*$',
            reg = RegExp(val, 'i'),
            text;

        $rows.show().filter(function () {
            text = $(this).text().replace(/\s+/g, ' ');
            return !reg.test(text);
        }).hide().filter(function () {

            $(".nada").show();

        });

    });

});

But there is a problem: even if I only return a value equal to what is typed, it falls in hide() and shows $('.nada').show() .

How can I fix this?

    
asked by anonymous 23.11.2018 / 11:35

1 answer

1

You can use this function by passing the searched value and where to search:

 function busca(value,targetSelector){
        $(targetSelector).show();
        $(targetSelector+':not(:contains("'+ value +'"))').hide();
    }
    

    $('#search').keyup(function () {
       busca($(this).val(), '.linhas');
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td>Nome</td><td>Sobrenome</td></tr><trclass="linhas">
  <td>paulo</td>
  <td>guina</td>
</tr>
<tr class="linhas">
  <td>jailson</td>
  <td>mendes</td>
</tr>
<tr class="linhas">
  <td>silas</td>
  <td>malafaia</td>
</tr>
<tr class="linhas">
  <td>marcos</td>
  <td>feliciano</td>
</tr>

</table>
<input id="search" placeholder="buscar">

The function will show everything and then hide what does not contain the text.

  

link

    
23.11.2018 / 16:21