0

this is my scenario ; I have an html as below, how can I highlight the search term in the results using Javascript ?

I mean when I type : Ho -> the first 2 letter of HOME will be highlighted. If I search for HOME : the whole word in the result will be highlighted.

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221

1 Answers1

1

Here is a very basic example:

HTML

Search: <input id="test"/>
<ul id="results"></ul>

Javascript

var results = ["Result1 Description", "Result2 Description", "Result3 Description"];

$("#test").change(function(){
    $("#results").empty();
var searchTerm = $(this).val();


for(var i = 0; i < results.length; i++){
    if(results[i].indexOf(searchTerm) != -1){

        $("#results").append("<li>"+ results[i].replace(searchTerm, "<span class=\"wrap\">" + searchTerm + "</span>") + "</li>");
    }
}
});

Working Example http://jsfiddle.net/t3BZ6/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • @BrianTimJesus Are you viewing the example or copying and pasting the code? In the example, try typing `sult` in the textbox then firing the change event by pressing tab. – Kevin Bowersox Jul 08 '13 at 08:14