Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery simple search suggestion text highlight

Tags:

jquery

I am trying to make a simple jQuery word search based on an input of type text and highlighting text. How can I do this for multiple words? This code is only working for a single character.

Html

<input type="text"/>

<div>John Resig
    George Martin
    Malcom John Sinclair
    J. Ohn 
    Sample text
</div>

CSS

span {    
    background : red 
}

JS

$("input").keyup(function() {
     var mysearchword = $("input:text").val();    
     var word = mysearchword;
     $( "div:contains('"+word+"')" ).html(function(i,html) {
         var re = new RegExp(word,"g");
         return html.replace(re,'<span>'+word+'</span>')
     });
});

JsFiddle

like image 417
PRANAV Avatar asked Jun 30 '15 08:06

PRANAV


1 Answers

If you have a predefined set of elements to target then

var $para = $('.para')
$("input").keyup(function() {
  $para.find('span.highlight').contents().unwrap();
  var mysearchword = this.value.trim();
  if (mysearchword) {
    var re = new RegExp('(' + mysearchword.trim().split(/\s+/).join('|') + ')', "gi");
    $para.html(function(i, html) {
      return html.replace(re, '<span class="highlight">$1</span>')
    });
  }
});
span.highlight {
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<div class="para">John Resig George Martin Malcom John Sinclair J. Ohn Sample text</div>
like image 126
Arun P Johny Avatar answered Nov 03 '22 08:11

Arun P Johny