-1

I wanna to live search in page and filter match case. Because of that I use :contains to search text in page. At first I want to find .col-3 that match with search text and after that I want to hide other siblings element. Now I understand siblings() not work correctly. It's a sample code:

$(document).ready(function(){

  $(':text').on('change paste keyup',function(){
     var val = $(this).val();
     $('.col-3').css({'background':'#fff','color':'#000'});  

     if(val != ''){
         var el = $('.col-3:contains('+val+')').css('color','blue');
         el.siblings('.col-3').css('background','red');
     } 

  })

 })

What should I do?

This is Complete Code

https://codepen.io/essvision/pen/MGmZKq?editors=1010

Ehsan Ali
  • 1,362
  • 5
  • 25
  • 51
  • 2
    Please post the relevant HTML. Codepens/Fiddles etc should be supplementary, not key to understanding the question. – Mitya May 02 '18 at 14:38
  • I added codepen sample, pay attention to bottom of question [https://codepen.io/essvision/pen/MGmZKq?editors=1010](https://codepen.io/essvision/pen/MGmZKq?editors=1010) – Ehsan Ali May 02 '18 at 14:40
  • Pay attention to the above comment - links to code pen must be accompanied by the relevant code in the question itself – Pete May 02 '18 at 14:47

1 Answers1

1

If the selector selected multiple items at the same time, hence type "h" can result 3 matches result, their sibling items will overlap with each other, which cause your problem. You can use :not(:contains) instead.

$(document).ready(function(){
  
  $(':text').on('change paste keyup',function(){
      var val = $(this).val();
      $('.col-3').css({'background':'#fff','color':'#000'});  
    
      if(val != ''){ 
          var el = $('.col-3:contains('+val+')').css('color','blue'); 
          $('.col-3:not(:contains('+ val +'))').css('background','red');
      } 
    
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>

  <input type="text">
  
  <div class="row">
    <div class="col-3">
      <h3>ehsan</h3>
      <p>expert</p>
    </div>
    <div class="col-3">
      <h3>mahdi</h3>
      <p>employee</p>
    </div>
    <div class="col-3">
      <h3>farhad</h3>
      <p>manager</p>
    </div>
    <div class="col-3">
      <h3>sara</h3>
      <p>employee</p>
    </div>
  </div>
  
</body>
</html>
Eliellel
  • 1,426
  • 1
  • 9
  • 14