Javascript filter

Asked

Viewed 452 times

1

I have the script below that aims to search for the text of the blocks, but the search is performed only until the first paragraph, then does not find the word, for example: search by coast and silva, does not find this word, but it exists.

<script>
$(function(){ 

  $("#filtro").keyup(function(){
    var texto = $(this).val();
    
    $(".bloco").each(function(){
      var resultado = $(this).text().toUpperCase().indexOf(' '+texto.toUpperCase());
      
      if(resultado < 0) {
        $(this).fadeOut();
      }else {
        $(this).fadeIn();
      }
    }); 

  });

});
</script>
<DOCTYPE html>
<html>
	<meta charset="UTF-8"/>
	<link rel="stylesheet" type="text/css" href="estilo.css"/>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
	<script type="text/javascript" src="script.js"></script> 	
<head>
</head>
<body>

<div class="busca">
   <input id="filtro" type="text" placeholder="Busca Rápida">
</div>
<div class="blocos">
  <div class="bloco">
    <h3>meu nome</h3>
    <p>minha descricao</p>
	<p>meu bairro</p>
  </div>
  
  <div class="bloco">
    <h3>outro nome</h3>
    <p>outra descricao</p>
	<p>costa e silva</p>
  </div>
  
  <div class="bloco">
    <h3>nome</h3>
    <p>descricao</p>
	<p>joão costa</p>
  </div>
  
  <div class="bloco">
    <h3>nome</h3>
    <p>descricao</p>
	<p>costa e silva</p>
  </div>
  
  <div class="bloco">
    <h3>nome</h3>
    <p>descricao</p>
	<p>bairro</p>
  </div>
  
  <div class="bloco">
    <h3>nome</h3>
    <p>descricao</p>
	<p>bairro</p>
  </div>  

</div>

</body>
</html>

  • I believe you could take a look at REGEX in Javascript.

1 answer

4


You are using indexOf(' '+texto.toUpperCase()), but why the space before the text?

Note that your HTML is indented with spaces on the first and second lines, but the third line is indented with a tab, so you cannot find the text, because it is not preceded by a common space, but rather a tab.

Your option is to change the indentation, or the method you do the search.

Browser other questions tagged

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