jQuery: Remove table row

Asked

Viewed 1,420 times

0

I am trying to remove the rows from the table where, in the Employee column, the name does not contain the "oã" sequence, as I did in the code below. The problem is that even returning false to the comparison if "oã" is contained in "José", the line is not excluded.

inserir a descrição da imagem aqui

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
  <table>
    <thead>
      <tr>
        <th>Código</th>
        <th>Funcionário</th>
        <th>Cargo</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>João</td>
        <td>Analista de Sistemas</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Maria</td>
        <td>Advogada</td>
      </tr>
      <tr>
        <td>3</td>
        <td>José</td>
        <td>Engenheiro Civil</td>
      </tr>
      <tr>
        <td>4</td>
        <td>Joãozinho</td>
        <td>Desenvolvedor</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

JS:

(function(){
    $(document).ready(function(){
        $('table td:nth-child(2)').each(function(indice){
            var txtDigitado = "Oã";
            var pattern = new RegExp(txtDigitado, 'i');

            var item_celula = $(this).text();

            if(pattern.test(item_celula)) {
              $('table tbody tr').eq(indice+1).remove();
            }
        });
    });
})();
  • Do you have any button on the line? Or this removal is static?

  • Hello Marconi. It’s static. Actually the variable "txtDigited" will pick up the value typed in the field, but I did so ai to summarize.

1 answer

3


Buddy, I had to modify your function a little bit, but I think it worked. I first took the row of the table we want to delete, looped it and applied its test. When it returns 'false' the row is deleted:

(function(){
    $(document).ready(function(){
        //pega a 'tr' no corpo da tabela
        $('table tbody tr').each(function(indice){
            var txtDigitado = "Oã";
            var pattern = new RegExp(txtDigitado, 'i');

            //pega o texto na 2a. 'td'
            var item_celula = $(this).find('td:eq(1)').text();

            if(pattern.test(item_celula) == false) {
                //caso passe no teste, remove a linha atual
                $(this).remove();
            }
        });
    });
})();

I hope I’ve helped.

  • Thanks Hugo! helped me a lot.

Browser other questions tagged

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