1

I used this:

$('#srch').click(function(){
  var s='';
  s = $('#gt').val();
  if (s == '')
  {
    $("p") .addClass("default");
  } else {
    $("p:contains('"+ s +"')") .addClass("active");
  }
});

Its working but it keep on storing the previous data. I want the previous data to be cleared.

Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
Aditya_kr
  • 175
  • 1
  • 13
  • Please see this - [http://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word](http://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word) – Balraj Singh Apr 20 '17 at 10:23
  • Please see this - [http://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word](http://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word) – Balraj Singh Apr 20 '17 at 10:26

4 Answers4

1

Use removeClass() to remove the highlighted element class

$('#srch').click(function(){
$("p").removeClass("active"); 
...
}
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

To clear input after search just use $(...).val(''):

$('#srch').click(function(){
    var s='';   
    s = $('#gt').val();
    $('#gt').val('');
    if (s == ''){       
        $("p") .addClass("default");    
    } else{
        $("p:contains('"+ s +"')") .addClass("active"); 
    }
});
Sojtin
  • 2,714
  • 2
  • 18
  • 32
0

Check this

 $('#srch').on("click",function(){
    var s = $('#gt').val();
    $("p").removeClass("active")
    if (s == ''){       
        $("p").addClass("default");    
    } else{
        $("p:contains('"+ s +"')").addClass("active"); 
    }
});

Working Fiddle Demo

S B
  • 1,363
  • 12
  • 21
0

Using ternary operator you can do this in single line .

$('#srch').click(function(){
    $("p") .removeClass("active") ;
    var s='';   
    s = $('#gt').val();
    s == ''?  $("p") .addClass("default")  : $("p:contains('"+ s +"')") .addClass("active"); 
});
.default {
  background: green;
}
.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a test contain</p>
<input type='text' id='gt'/>
<input type='button' id='srch'>
4b0
  • 21,981
  • 30
  • 95
  • 142