4
respostas

Pesquisa mas com condições

Olá! Estou fazendo um campo de busca em uma tabela no qual eu posso digitar o nome da loja (primeira coluna) e é retornado todas as linhas que correspondem à busca.

Mas eu também gostaria que, caso eu digitasse o CEP, retornasse as linhas correspondentes a este CEP.

Já tentei diversas formas, mas ou ele retorna o resultado correspondente à primeira coluna, ou ele retorna apenas o correspondente à última coluna, que é onde está o Google Maps com a localização da loja.

Já tentei fazer 2 funções diferentes mas o "onclick" do botão pesquisar considera apenas a última função chamada, ignorando a primeira.

Meu código é esse:

function pesquisar() {
  // Declaração de variáveis.
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table");
  tr = table.getElementsByTagName("tr");

for (i = 0; i < tr.length; i++) {
  td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
};

E esta é uma das formas que eu tenho tentado fazer funcionar como eu quero, mas não funciona:

function pesquisar() {
  // Declaração de variáveis.
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table");
  tr = table.getElementsByTagName("tr");

  if (typeof input.value === 'string') {
  // Busca todas as linhas da tabela e esconde aquelas que não correspondem à busca.
  for (i = 0; i < tr.length; i++) {
  td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
  } else {
    for (i = 0; i < tr.length; i++) {
  td = tr[i].getElementsByTagName("td")[2];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }  
}
};

Alguém poderia me dar uma luz? :)

4 respostas

Boa noite,

Eu utilizo jQuery.

jQuery:

$("#Input").on("keyup blur", function() {
    var value = $(this).val().toLowerCase();
        $("#table tbody tr").filter(function() {
              $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
  });

HTML:

<input type="search" placeholder="" class="form-control" id="Input">
<table class="table" id="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
  </tbody>
</table>

Espero ter ajudado.

Olá! Obrigado pela ajuda!

Esqueci de avisar... A plataforma que eu uso não superta JQuery... Saberia adaptar esse código pra JavaScript?

Boa tarde,

Uma pequena alteração que é feita no primeiro código.


function pesquisar() {
  // Declaração de variáveis.
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table");
  tr = table.getElementsByTagName("tr");

for (i = 0; i < tr.length; i++) {
  td = tr[i];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
};

Espero ter ajudado.

Desculpa a curiosidade, mas que plataforma que usa para não aceitar jQuery?

Ajudou! Até funcionou mas por algum motivo a primeira linha, a que tem os títulos das colunas, some! Mas eu devo conseguir resolver isso

Estou usando o OCC, Oracle Commerce Cloud. Estranho mesmo não poder usar Ajax.

Aproveitando, vc sabe como eu poderia alterar esse código pra quando eu digitar o CEP, aparecer as linhas correspondentes? O problema é que não tem nenhuma linha com o CEP, só tem a nona coluna que tem um link pro google maps. Tenho procurado a dias, já li tutoriais sobre a API de Geolocalização da Google e até aprendi a usar, mas não consigo adaptar pro meu código, de fazer ele funcionar pra filtrar a tabela. Como pegar a latitude e longitude da URL no googlemaps e transformar em CEP...

Tem mais alguma dica valiosa? :D

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software