Real-time search with jQuery

Asked

Viewed 308 times

0

I have the following code to do a real-time search with jQuery, searching for values within 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 you return only one value equal to the one that is typed, it falls into the hide() and shows the $('.nada').show().

How can I fix this?

  • I don’t know if it helps you or if you can use a jquery lib for this but I use this one: https://mottie.github.io/tablesorter/docs/example-option-theme-bootstrap-v4.html

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>
<tr class="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.

https://api.jquery.com/contains-selector/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.